在学习vue的axios时,访问自己的本地数据出现了跨域问题,如下图
主要代码有
var root = 'http://172.16.188.107:8080/im'
、、、
getData() {
this.$api.get('/data1.json', null, r => {
console.log(r);
}, f => {
console.log(f);
})
}
如何解决这个问题呢?其实非常好办,那就是将接口代理到本地。
配置webpack将接口代理到本地
其实,vue-cli脚手架工具,已经充分的考虑到这个问题,我们只要进行简单的设置,就能实现我们的目的。
我们打开config/index.js文件,找到以下代码:
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: true,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
// Use Eslint Loader?
// If true, your code will be linted during bundling and
// linting errors and warnings will be shown in the console.
useEslint: true,
// If true, eslint errors and warnings will also be shown in the error overlay
// in the browser.
showEslintErrorsInOverlay: false,
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
其中,proxyTable:{},这一行,就是给我们配置代理的。
根据我们要访问的接口,我们把这里调整为:
proxyTable: {
'/im':{
target: 'http://172.16.188.107:8080', // 你接口的域名
//secure: false, //如果是https接口,需要配置这个参数
changeOrigin: false,
}
}
配置完以后再修改一下之前上面的代码,就可以了。
var root = '/im'