如果我们在组件中发起axios请求后台服务器的数据,两台服务器的端口号不相同,显然会存在跨域问题。例如此处我们向端口号为5000的服务器发起axios请求
axios.get('http://localhost:5000/students').then(
response=> {
console.log('请求成功了',response)
},
error => {
console.log(error)
}
)
}
直接用一个事件来触发上面的请求,会报如下错误:
因此在这里就需要配置一下代理服务器:在vue.config.js文件中添加如下代码
devServer: {
proxy: 'http://localhost:5000'
}
再将最上面的代码请求端口改为8080
axios.get('http://localhost:8080/students').then(
response=> {
console.log('请求成功了',response)
},
error => {
console.log(error)
}
)
}
之后再重新启动一下项目 请求成功