1。在main.js中引入 axios 配置 baseURL
Vue.prototype.$axios = axios
axios.defaults.baseURL = '/api' //关键代码
2。在config文件夹下的index.js文件中的proxyTable字段中
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
//***************************************** */
'/api': {
target: 'http://liangengine.gitee.io/json/', // 你请求的第三方接口
changeOrigin: true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
pathRewrite: { // 路径重写,
'^/api': '' // 替换target中的请求地址,也就是说以后你在请求http://liangengine.gitee.io/json/XXXXX这个地址的时候直接写成/api即可。
}
}
//***************************************** */
},
// 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: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
/**
* 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
},
3.在具体使用axios的地方,修改url如下即可:
this.$axios("/index.json").then(res => {
console.log(res);
})
.catch(error => {
console.warn(error);
});
(配置好重新启动就可以。)
原理:
因为我们给url加上了前缀/api,我们访问/movie/top250就当于访问了:localhost:8080/api/movie/top250(其中localhost:8080是默认的IP和端口)。
在index.js中的proxyTable中拦截了/api,并把/api及其前面的所有替换成了target中的内容,因此实际访问Url是http://api.douban.com/v2/movie/top250。
浙公网安备 33010602011771号