在使用Vue开发项目时,由于先后端分离,常常遇到跨域请求的问题,通用的方法是在后端设置Access-Control-Allow-Origin:*。但在某些特殊状况下,这个方式并不适用,这种时候,能够经过设置webpack的proxyTable进行解决(仅限于开发环境)。
使用vue-cli建立的项目中,能够看到config/index.js文件中,proxyTable默认为空:vue
首先使用一些免费的API进行测试:https://github.com/jokermonn/...webpack
设置以下:ios
proxyTable: { '/article/today': { //访问路由 target: 'https://interface.meiriyiwen.com', //目标接口域名 secure: false, //https协议才设置 changeOrigin: true, //是否跨域 } }
使用axios进行请求:git
import axios from 'axios'; export default { name: 'App', mounted(){ this.getInfos(); }, methods:{ getInfos() { axios.get('/article/today').then((res)=>{ console.log(res); }) } } }
然而,请求失败了,报404错误!这个时候,只须要从新执行 npm run dev 便可!github
此次,请求成功了,本地访问 http://localhost:8081/article/today 其实就是代理访问了https://interface.meiriyiwen....web
如今有个问题,想要把这个请求地址写成“/api”开头,怎么办?vue-cli
设置以下:npm
proxyTable: { '/api': { //访问路由 target: 'https://interface.meiriyiwen.com', //目标接口域名 secure: false, //https协议才设置 changeOrigin: true, //是否跨域 pathRewrite: { '^/api/article': '/article/today' //重写接口 }, } }
axios请求更改以下:axios
axios.get('/api/article').then((res)=>{ console.log(res); })
访问成功了:后端
若是想设置多个代理,proxyTable能够这样设置:
proxyTable: { '/api': { //访问路由 /api 触发 target: 'https://interface.meiriyiwen.com', //目标接口域名 secure: false, //https协议才设置 changeOrigin: true, //是否跨域 pathRewrite: { '^/api/article': '/article/today' //重写接口 }, }, '/movie' : { //访问路由 /movie 触发 target: 'https://api.douban.com', secure: false, changeOrigin: true, //是否跨域 pathRewrite: { '^/movie': '/v2/movie/in_theaters' //原接口地址太长了,重写能够缩短些 } } }
Axios请求以下:
//实际访问地址为:https://interface.meiriyiwen.com/article/today axios.get('/api/article').then((res)=>{ console.log(res); }); //实际访问地址为:https://api.douban.com/v2/movie/in_theaters axios.get('/movie').then((res)=>{ console.log(res); });
没错,相信你的眼睛,请求成功了!