vue-cli3.0 axios跨域请求代理配置方式及端口修改
作者:Stavin Li
这篇文章主要介绍了vue-cli3.0 axios跨域请求代理配置方式及端口修改,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
vue-cli3.0 axios跨域请求代理配置及端口修改
1.安装 axios
vue add axios
2.项目根目录下新建 vue.config.js
// vue.config.js
module.exports = {
devServer: {
port: 端口号,
proxy: {
'/apis': {
target: 'https://movie.douban.com/', // target host
ws: true, // proxy websockets
changeOrigin: true, // needed for virtual hosted sites
pathRewrite: {
'^/apis': '' // rewrite path
}
},
}
}
};3. 重启服务npm run serve
4. *.vue 文件中请求实例
this.axios.get('/apis/ithil_j/activity/movie_annual2017').then(res => {
console.log(res.data)
}, res => {
console.info('调用失败');
})vue-cli3.0解决跨域问题(超简单)
在根目录新建文件:vue.config.js

在文件新增内容:
module.exports = {
publicPath: '/',
outputDir: 'dist',
devServer: {
open: true,
host: 'localhost',
port: '8081',
proxy: {
'/api': {
target: 'http://localhost:8080', // 要请求的地址
ws: true,
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
};其中,http://localhost:8080是要请求的地址,可根据自己的需求更换。
这样配置之后,如果要请求http://localhost:8080/getFile这个url,只需像下面这样写ajax请求即可:
this.axios.get('/api/getFile', {//用api代替http://localhost:8080
}).then( response => {
window.console.log("成功" + response)
}).catch(
error => {
window.console.log("失败"+error)
})总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
