vue中使用axios请求API或其他域名地址时,会产生跨域请求问题,应该如何解决呢?(本文以请求API为例)
解决方法:
1、为axios设置请求头、拦截器等,这里直接对axios进行封装,将其封装在request.js文件中。
request.js文件:
import axios from 'axios'
const request = axios.create({
baseURL: '/api', //使用/api作为基地址
timeout: 5000
})
// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token,对请求参数统一加密
request.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/json;charset=utf-8';
// config.headers['token'] = user.token; // 设置请求头
return config
}, error => {
return Promise.reject(error)
});
// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
response => {
let res = response.data;
// 如果是返回的文件
if (response.config.responseType === 'blob') {
return res
}
// 兼容服务端返回的字符串数据
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
}
return res;
},
error => {
console.log('err' + error) // for debug
return Promise.reject(error)
}
)
export default request;
2、修改配置文件(两种格式)
(1)vue-cli版本是2.0左右的是webpack的config目录:
index.js文件:
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://localhost:9090', // 目标url
changeOrigin: true, // 是否跨域
pathRewrite: {
'^/api': '' // 其中/api等价于前面的目标地址
}
}
},
}
}
(2)vue-cli版本是3.0以上的就是vue.config.js,而不是config目录:
vue.config.js文件:
module.exports = {
devServer: {
open: true,
host: 'localhost',
port: 8080,
https: false,
//以上的ip和端口是我们本机的;下面为需要跨域的
proxy: { //配置跨域
'/api': {
target: 'https://query.asilu.com/weather', //填写请求的目标地址
changOrigin: true, //允许跨域
pathRewrite: {
'^/api': '' //请求的时候使用这个api就可以
}
}
}
}
}
3、使用axios请求API
// 挂载之前
beforeMount() {
//封装axios的时候,已经设置了/api作为基地址,所以在此没有添加/api
let httpURL = `/baidu/?city=${this.$route.params.city}`; //目标地址后接的详细地址
request.get(httpURL).then(function (res) {
console.log(res);
});
},
注意:修改了配置文件之后,记得重新run一遍,不然不生效!!!