
跨域方式怎么解决呢?我们可以使用proxy。
如果你的前端应用和后端API服务器没有运行在同一个主机上,你需要在开发环境下将API请求代理到API服务器。这个问题(说白了就是跨域的解决方案)可以用个vue.config.js中的devServer.proxy选项来配置。
devServer.proxy可以是一个指向开发环境API服务器字符串:
module.exports = {
devServer:{
proxy: ‘http://localhost:4000’//这里假设项目端口号非4000,而后端端口号为4000,从而造成了跨域
}
}我们打开项目,在vue.config.js添加如下代码:
module.exports = {
devServer:{
proxy: ‘http://localhost:4000’//这里假设项目端口号非4000,而后端端口号为4000,从而造成了跨域
}
}
然后前面axios请求就不需要加上域名了

axios.get(/getdata).then(function(response){
console.log(response)
}).catch(function(error){
console.log(error)
})上面那种方式只是针对单个接口的描述,也可以说是一种简写方式,但是我们做项目有时对接的可能是多个平台接口的形式,完整且多个接口的写法:
vue.config.js中的proxy配置:
module.exports = {
devServer:{
proxy: {
'/api’{
target:’ http://localhost:4000’,
changeOrigin:true,
pathRewrite:{
'^/api’:"/”
}
},
'/foo'{
target:'<other_url>',
}
}
}
}Axios请求接口
axios.get(/api/getdata).then(function(response){
console.log(response)
}).catch(function(error){
console.log(error)
})
关于简忆
简忆诞生的故事



粤ICP备16092285号
文章评论(0)