webpack提供了配置代理的方法解决跨域:
1、在vue-cli项目中打开webpack.dev.cof.js,如下:
devServer: { clientLogLevel: 'warning', historyApiFallback: { rewrites: [ { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') }, ], }, hot: true, contentBase: false, // since we use CopyWebpackPlugin. compress: true, host: HOST || config.dev.host, port: PORT || config.dev.port, open: config.dev.autoOpenBrowser, overlay: config.dev.errorOverlay ? { warnings: false, errors: true } : false, publicPath: config.dev.assetsPublicPath, proxy: config.dev.proxyTable, quiet: true, // necessary for FriendlyErrorsPlugin watchOptions: { poll: config.dev.poll, } }
2、打开conifg目录下的index.js,在 proxyTable中进行配置:
proxyTable: { '/api': { target: 'http://127.0.0.1:9999/',//设置你调用的接口域名和端口号,别忘了加http changeOrigin: true, secure: false, // 如果是https接口,需要配置这个参数 pathRewrite: { '^/api': '/'//这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add’即可 } } }
<script> export default { methods: { getData() { this.$axios .get("/api/blog/data/") .then(function(response) { console.log(response); }) .catch(function(error) { console.log(error); }); } } }; </script>