1.安装 npm install axios 2.在utils下新建一个axios文件用来配置axios
import axios from 'axios';
const qs = require('qs');
const service=axios.create({
baseURL: process.env.BASE_API, //请求公共地址,baseURL`将被添加到`url`,所以后边请求只需api的方式即可
timeout: 5000, //请求响应时间
})
// 是否携带cookie信息,默认为false,根据项目需求设置
service.defaults.withCredentials = true;
// 添加一个请求拦截器
service.interceptors.request.use(function (config) {
// 对请求数据做些事
if(config.method === 'post'){ //post传参序列化
config.data = qs.stringify(config.data);
}
return config;
}, function (error) {
return Promise.reject(error);
});
// 添加一个响应拦截器
service.interceptors.response.use(function (response) {
// 对响应数据做些事
return response;
}, function (error) {
console.log(error)
// Do something with response error
return Promise.reject(error);
});
export default service;
3.新建一个api文件,这里边存放所有的请求函数,方便查找管理
import axios from '../utils/axios';
// 首页banner
export function banner(){
return axios({
url:'/wxchat/xxx.action', //请求的地址
method:'POST'
})
}
// post请求带参数
export function qiang(activityStatusType){
return axios({
url:'/wxchat/xxx.action',
method:'POST',
data:{activityStatusType:activityStatusType}
})
}
// get请求
export function moneys(){
return axios({
url: '/sd-web/xxx',
method: 'get'
});
}
// get请求带参数
export function moneys(ids){
return axios({
url: '/sd-web/xxx',
method: 'get',
params:{id:ids}
});
}
4.页面实际应用
import {banner} from '../../api/api'; //在页面上引入需要的请求函数
//在生命周期函数或者需要的方法里运用
mounted() {
banner().then(response => {
this.banner=response.data.data.SlAdvertisTabList
}).catch(err=>{
console.log(err)
});
},
5.跨域配置
(1)在config文件夹写的index.js里配置跨域
proxyTable: {
'/wxchat': {
target: 'xxx', //目标接口域名
changeOrigin: true, //是否跨域
secure: false, //target默认情况下,不接受运行在HTTPS上,且使用了无效证书的后端服务器。如果你想要接受, 则需设置该项为false
// pathRewrite: { // 如果接口本身没有/wxchat需要通过pathRewrite来重写了地址 重写接口
// '^/wxchat: ' '
// }
}
},
注:我写的这个项目里,本身存在/wechat通用前缀,所以我没有用pathRewrite重写,如果你们接口里没有通用前缀的话,是要进行重写的 上面配置中,’^/wxchat’ 其实是一个正则表达式
‘^/wxchat’ 应该拆分成 ‘^’ 和 ‘/wxchat’ 两个字符串,其中 ‘^’ 匹配的是字符串最开始的位置。
‘/wxchat’: {}, 就是告诉node, 我接口只要是’/wxchat’开头的才用代理.所以你的接口就要这么写/wxchat/xx/xx. 最后代理的路径就是 xxx.xx.com/wxchat/xx/x…. 可是不对啊, 我正确的接口路径里面没有/wxchat啊. 所以就需要 pathRewrite,用’’^/wxchat’’:’’, 把’/wxchat’去掉, 这样既能有正确标识, 又能在请求接口的时候去掉wxchat
接口没有通用前缀的开发环境的配置
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
BASE_API: '"/wechat"', //在跨域里配置的//wechat,接口里就不用写通用前缀了,就按照正常接口写就可以了
})
接口有通用前缀的开发环境配置
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
BASE_API: '""', //这里为空就好了,通用前缀就写在接口里
})