Axios 是一个基于 promise 的 HTTP 库, 可以用在浏览器和 node.JS 中
axios 在项目中 (vue) 的使用
没有 vue 项目的使用 vue-cli 脚手架生成一个 webpack 模板的项目即可愉快的看下去了~
1, 安装 axios 到项目中
NPM install axios --save
配置 wepack 别名, 不同环境访问不同的配置接口(推荐: webpack 中文文档 https://www.html.cn/doc/webpack/ )
配置:
使用: import config from 'config'
2, 封装一个 axios 实例
新建 fetch.JS, 在此创建 axios 实例与过滤器
若配置了代理. 则 config.apiBaseUrl 则配置代理的前缀即可
- import config from 'config'
- import axios from 'axios'
- // import qs from 'qs';
- const instance = axios.create({
- baseURL: config.apiBaseUrl, // API 的 base_url
- timeout: 10000, // 请求超时时间
- // transformRequest: data => qs.stringify(data)
- });
axios 默认提交格式为: application/JSON, 转换后提交格式为 application/x-www-form-urlencoded
在 ASP.NET core 中, 需要在 action 方法上添加 [FromBody] 接收 JSON 格式的数据, 正常的都是 application/x-www-form-urlencoded 故有此修改.
按照使用需要安装 qs 到项目中, 可转换数据格式类型
NPM install qs --save
使用 qs 转换请求对比图
3, 给实例添加拦截器
- // 添加请求拦截器
- instance.interceptors.request.use(function (config) {
- // 在发送请求之前做些什么
- return config;
- }, function (error) {
- // 对请求错误做些什么
- return Promise.reject(error);
- });
- // 添加响应拦截器
- instance.interceptors.response.use(function (response) {
- // 对响应数据做点什么
- return response;
- }, function (error) {
- // 对响应错误做点什么
- return Promise.reject(error);
- });
- // 最后暴露实例
- export default instance
4, 实例的调用
若配置了 express 代理, 请求路径为: 浏览器 ->express 开发服务器 ----- 发送请求 ---->接口服务器
- import fetch from 'fetch.js'
- //get
- fetch({
- url:'/home/data',// 完整的请求路径为 fetch.JS 配置的 baseURL+/home/data?pageIndex=1
- method:'GET',
- params:{pageIndex:1}
- })
- //post
- fetch({
- baseURL:'/api/v1',// 完整的请求路径为 / API/v1/home/save
- url:'/home/save',
- method:'POST',
- data:{id:1}
- })
本文来自 vue.js 答疑 https://www.html.cn/qa/vue-js/ 栏目, 欢迎学习!
来源: http://www.css88.com/qa/vue-js/14696.html