同源策略,跨域,不管是工作还是面试都是不可回避的问题,在vue cli中,是如何来解决跨域问题的?

vue cli 可以在 vue.config.js 中配置 webpack 相关信息,可以利用 webpack 请求代理来解决此问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// vue.config.js
module.exports = {
runtimeCompiler: true,
publicPath: '/', // 设置打包文件相对路径
devServer: {
// port: 8071, // 自定义启动端口
// open: true, // 配置自动启动浏览器
proxy: {
'/api': {
target: 'http://127.0.0.1:8100/', // 对应自己的接口
changeOrigin: true,
ws: true,
pathRewrite: {
'^/api': ''
}
}
}
},
}

接下来配置 axios 请求;

1
2
3
4
5
6
7
8
9
10
// main.js
axios.defaults.timeout = 5000 // 请求超时
axios.defaults.baseURL = '/api/' // api 即上面 vue.config.js 中配置的地址

// 发送请求
axios.post('/postData/', { // 请求:http://localhost:8080/api/postData
name: 'cedric',
}).then((res) => {
console.log(res.data)
})

生产环境下,只需要修改 axios 配置即可,其余不需要改变;

1
2
3
4
5
6
7
8
9
10
// 生产环境
axios.defaults.timeout = 5000 // 请求超时
axios.defaults.baseURL = 'http://api.demourl.com/'

// 页面中axios的请求保持不变:
axios.post('/postData/', {
name: 'cedric',
}).then((res) => {
console.log(res.data)
})

再补充一个 axios 配置时候遇到的一个小问题,在调用后台 delete 方法的时候总是报403/401的错误,究其原因,是在配置 axios 请求头的时候把 token 用这种方式给写死了,这就导致传到后台的 token 还是上一次的旧 token

1
axios.defaults.headers['token'] = sessionStorage.getItem('token');

解决办法是需进行请求拦截,这样就可以获取到实时的 token 了

1
2
3
4
5
axios.interceptors.request.use(req =>{
let token = sessionStorage.getItem('token') || '';
req.headers.common['token'] = token
return req;
})