一、后端配置cors响应头
缺点 任何人都可以连接该服务要数据
二、jsonp
借助script 的src属性
只能Get请求
前后端都得配置麻烦
三、nginx
四、vue-cli脚手架
方式一
devServer: {
proxy: 'http://localhost:4000'
}
方式二
devServer: {
proxy: {
'/api': {
target: 'http://localhost:9400',
ws: true,
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
},
'/foo': {
target: 'http://localhost:5400'
}
}
}
target填写需要代理的目标服务器,例如需要从服务器http://localhost:9400/test获取数据axios.get('http://localhost:9400/api/test').then(res => {})
,但是跨域了,target填写http://localhost:9400,就会产生一个http://localhost:8080代理服务器,代码中请求数据就可以这么写axios.get('http://localhost:8080/api/test').then(res => {})