一、推荐
1. 原生ajax
2. fetch
- 概念
fetch号称是ajax的替代品,它的API是基于Promise设计的
旧版本的浏览器不支持Promise,需要使用polyfill es6-promise - 缺点
fetch是比较底层的API,很多情况下都需要我们再次封装
比如:① 手动参数拼接② fetch不支持超时控制
3. axios
- 特性
① 从浏览器中创建 XMLHttpRequest
② 从 node.js 发出 http 请求
③ 支持 Promise API
④ 拦截请求和响应
⑤ 转换请求和响应数据
⑥取消请求
⑦ 自动转换JSON数据
⑧客户端支持防止 CSRF/XSRF - 支持多种请求方式
axios(config) axios.request(config) axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.post(url[ data [, config]]) axios.put(url[ data [, config]])
3)名称由来
ajax i/o system
4. 测试接口
http://demo.itlike.com/web/xlmc/api/homeApi/categoriesdetail/lk001
http://demo.itlike.com/web/xlmc/api/homeApi/categoriesdetail/lk002
二、axios使用
- 安装
yarn add axios
- 简单使用
① get请求操作:参数用params
② post请求操作:参数用dataaxios({ method: 'get', url: 'http://demo.itlike.com/web/xlmc/api/homeApi/categoriesdetail/lk001', // 参数传递 params: { name: '张三', age: 18 } }).then((res) => { console.log(res); }).catch((err) => { console.log(err); }).finally(() => { })
③ 并发请求axios({ method: 'post', url: 'http://demo.itlike.com/web/xlmc/api/homeApi/categoriesdetail/lk001', // 参数传递——data data: { name: '张三', age: 18 } }).then((res) => { console.log(res); }).catch((err) => { console.log(err); }).finally(() => { })
1. axios.all,可以放入多个请求的数组
2. axios.all返回的结果是一个数组,可以使用axios.spread将数组的值展开
也可以通过axios.spread()拆解分割axios.all([ axios({ url: "http://demo.itlike.com/web/xlmc/api/homeApi/categoriesdetail/lk001" }), axios({ url: "http://demo.itlike.com/web/xlmc/api/homeApi/categoriesdetail/lk002" }) ]).then((result) => { console.log(result); }).catch((error) => { console.log(error); })
④ 常用的配置选项axios.all([ axios({ url: "http://demo.itlike.com/web/xlmc/api/homeApi/categoriesdetail/lk001" }), axios({ url: "http://demo.itlike.com/web/xlmc/api/homeApi/categoriesdetail/lk002" }) ]).then(axios.spread((res1, res2) => { console.log(res1); console.log(res2); }));
在组件中配置当前axios的根路径的话,直接在componentDidMount()
钩子中进行配置-
请求地址
javascript url: '/itlike'
-
请求类型
method: 'get'
-
请求根路径
baseURL: 'http://www.itlike.com'
当前组件全局配置
componentDidMount() { // 当前组件axios配置 axios.defaults.baseURL = 'http://demo.itlike.com/web/xlmc/api' }
-
请求前数据处理
transformRequest: [function (data, headers) { return data; }],
-
请求后数据处理
transformResponse: [function (data) { return data; }],
-
自定义请求头
headers: {'X-Requested-With': 'XMLHttpRequest'}
-
URL查询对象
params: { ID: 12345 }
-
URL查询对象序列化
paramsSerializer: function (params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) } request body data: { firstName: 'Fred' }
-
超时设置
timeout: 1000ms
-
跨域是否带token
withCredentials: false
-
自定义请求处理
adapter: function (config) { /* ... */ }
-
身份验证
auth: { username: 'janedoe', password: 's00pers3cret' }
-
响应数据规则
responseType: 'json' 'arraybuffer', 'document', 'json', 'text', 'stream'
⑥ 封装Ajax发起axios请求axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
⑦ 使用axios拦截器import axios from 'axios' export default function ajax(url = '', params = {}, type = 'GET') { // 0. 变量 let promise; // 1. 返回Promise return new Promise((resolve, reject) => { // 1.1 判断请求类型 if (type.toUpperCase() === 'GET') { //GET promise = axios({ url, params }) } else if (type.toUpperCase() === 'POST') { // POST promise = axios({ method: 'post', url, data: params }) } // 1.2 处理结果并返回 promise.then((response) => { resolve(response); }).catch((error) => { reject(error); }) }) }
- 概念:axios提供了拦截器,用于在每次发送请求前或者得到响应后,进行对应的处理。共4个拦截① 请求成功② 请求失败③ 响应成功④ 响应失败
- 实操
① 配置请求拦截器
② 配置响拦截器axios.interceptors.request.use((config) => { console.log(config); // 1.一些请求统一加token // 2.统一设置符合服务器要求的config信息 // 3. 在每次请求前,加上请求动画 // 注意:一定要返回,不然会卡在这里 return config; }, error => { console.log(error); return Promise.error(error); });
axios.interceptors.response.use((response) => { console.log('-----'); console.log(response); console.log('-----'); // 如果返回的状态码为200,说明接口请求成功,可以正常拿到数据,否则的话抛出错误 if (response.status === 200) { return Promise.resolve(response.data); } else { return Promise.reject(response); } }, (error) => { console.log(error); });
-
http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.billboard.billList&type=1&size=10&offset=0
-
解决方案
① 方案1
在package.json中配置"proxy": "http://tingapi.ting.baidu.com"
ajax('/v1/restserver/ting', {method: 'baidu.ting.billboard.billList', type: 1, size: 10, offset: 0}).then(result => { console.log(result); }).catch(error => { console.log(error) })
② 方案2
借助中间件http-proxy-middleware
-
yarn add http-proxy-middleware
-
create src/setupProxy.js
-
const { createProxyMiddleware } = require('http-proxy-middleware'); module.exports = function(app) { app.use( '/api', createProxyMiddleware({ target: 'http://tingapi.ting.baidu.com', changeOrigin: true, }) ); };
-
-