Axios
Axios 是一个基于 promise 网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。
服务器端
使用json-server
1. axios基本使用
| |
| axios({ |
| method: 'GET', |
| url: 'http://localhost:3000/posts/2' |
| }).then(res => { |
| console.log(res); |
| }) |
| |
| |
| axios({ |
| method: 'POST', |
| url: 'http://localhost:3000/posts', |
| data: { |
| title: 'test', |
| author: 'lll' |
| } |
| }).then(res => { |
| console.log(res); |
| }) |
| |
| |
| axios({ |
| method: 'PUT', |
| url: 'http://localhost:3000/posts/3', |
| data: { |
| title: 'test', |
| author: 'new-lll' |
| } |
| }).then(res => { |
| console.log(res); |
| }) |
| |
| |
| axios({ |
| method: 'DELETE', |
| url: 'http://localhost:3000/posts/3', |
| }).then(res => { |
| console.log(res); |
| }) |
2. 其他请求方法
| axios.request(config) |
| axios.get(url[, config]) |
| axios.delete(url[, config]) |
| axios.head(url[, config]) |
| axios.options(url[, config]) |
| axios.post(url[, data[, config]]) |
| axios.put(url[, data[, config]]) |
| axios.patch(url[, data[, config]]) |
| |
| |
| axios.request({ |
| method: 'GET', |
| url: 'http://localhost:3000/posts/2' |
| }).then(res => { |
| console.log(res) |
| }) |
| |
| |
| axios.post( |
| 'http://localhost:3000/comments', |
| { |
| "body": "other", |
| "postId": 2 |
| } |
| ).then(res => { |
| console.log(res) |
| }) |
3. axios默认配置
| |
| axios.defaults.method = 'GET' |
| axios.defaults.baseURL = 'http:localhost:3000' |
| axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; |
| axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; |
4. axios创建实例对象
| |
| const obj = axios.create({ |
| baseURL: 'http://localhost:3000' |
| }) |
| |
| obj({ |
| url: 'posts/2' |
| }).then(res => { |
| console.log(res) |
| }) |
5. axios拦截器
| |
| |
| |
| |
| |
| |
| axios.interceptors.request.use(functio(config) { |
| console.log('req success') |
| return config |
| }), function (error) { |
| console.log('req fail') |
| return Promise.reject(error) |
| } |
| |
| |
| axios.interceptors.response.use(functio(response) { |
| console.log('res success') |
| return response; |
| }, function (error) { |
| console.log('res fail') |
| return Promise.reject(error); |
| }); |
6. 取消请求
| let cancel = nul |
| btns[0].onclick = function () { |
| |
| if (cancel !== null) { |
| cancel() |
| } |
| axios({ |
| url: '/posts', |
| cancelToken: new axios.CancelTok(function executor(c) { |
| cancel = c; |
| }) |
| }).then(res => { |
| cancel = null |
| console.log(res) |
| }) |
| btns[1].onclick = function () { |
| cancel() |
| } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析