Axios

  • Axios已关闭评论
  • 59 次浏览
  • A+
所属分类:Web前端
摘要

Axios 是一个基于 promise 网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。


Axios

Axios 是一个基于 promise 网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。

服务器端

使用json-server

1. axios基本使用

// 1.GET axios({     method: 'GET',     url: 'http://localhost:3000/posts/2' }).then(res => {     console.log(res); })  // POST axios({     method: 'POST',     url: 'http://localhost:3000/posts',     data: {         title: 'test',         author: 'lll'    } }).then(res => {     console.log(res); })  // PUT axios({    method: 'PUT',     url: 'http://localhost:3000/posts/3',     data: {         title: 'test',         author: 'new-lll'     } }).then(res => {     console.log(res); })  // DELETE 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]])  // request axios.request({     method: 'GET',     url: 'http://localhost:3000/posts/2' }).then(res => {     console.log(res) })  // POST axios.post(     'http://localhost:3000/comments',     {         "body": "other",        "postId": 2     } ).then(res => {     console.log(res) }) 

3. axios默认配置

// default setting 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实例和axios对象几乎相同 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() } 
  • 版权声明:本站原创文章,于2023年2月8日14:56:21,由 发表,共 2076 字。
  • 转载请注明:Axios - 张拓的天空