# Vue 中用 axios 配置跨域
# 1. 为什么要跨域
首先,Vue 的默认端口号是 8080,在访问其他端口号的服务器的过程中,可以成功发送请求到对方服务器,但是虽然对方接受到了请求,由于不同服务器的原因,会阻截回传数据,故虽然能成功发送请求但是不能成功的接收到数据。
# 2. 如何配置跨域
在 Vue 脚手架中会调用虚拟服务器,在 Vue.config.js 文件中
配置跨域的两种方式都在下列代码中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| module.exports = { lintOnSave: false, devServer: { proxy: { '/api1': { target: "http://localhost:5000", pathRewrite: { '^/api1': '' }, wb: true, changeOrigin: false, }, '/api1': { target: "http://localhost:5000", pathRewrite: { '^/api1': '' }, wb: true, changeOrigin: false, }, } } devServer:{ proxy:"http://localhost:5000", } }
|
# 3. 如何发送请求
配置完跨域以后并不是向对应端口号发送请求,而是依然向 8080 端口号发送请求,然后由代理服务器向目标服务器发送请求
1 2 3 4 5 6 7 8 9 10
| getStudent(){ axios.get('http://localhost:8080/api1/students').then( response=>{ console.log('访问成功',response.data); }, error=>{ console.log('呜呜呜,访问失败',error.massage); } ) },
|
但是有一个问题,即如果在 8080 端口号中也存在 students 的数据,那么将不会跨域发送请求,而是在本端口号进行发送请求获取数据