简述
环境: Vue-CLI@4
假设接口的地址为 http://localhost:5000/api/ctrip/plan?deaprtureTime=2020-10-02&dcity=上海&acity=乌鲁木齐
。
前端地址为 http://localhost:8080
在vue.config.js中设置proxy,vue.config.js和package.json同级,若没有则自己新建。 在以下的例子中,/spider
,作为请求接口的前缀,以及匹配使用的proxy,将axios的bashUrl设置为/spider
,然后通过pathRewrite把这个重写掉,因为我们实际的请求中并没有这个。在下面的例子里,axios请求的地址为 /spider/api/ctrip/plan?deaprtureTime=2020-10-02&dcity=上海&acity=乌鲁木齐
,通过proxy请求的 http://localhost:8080/spider/api/ctrip/plan?deaprtureTime=2020-10-02&dcity=上海&acity=乌鲁木齐
,这个在浏览器的开发者工具里看到的也是这个。然后实际去请求数据的地址是 http://localhost:5000/api/ctrip/plan?deaprtureTime=2020-10-02&dcity=上海&acity=乌鲁木齐
。
假设使用"/api",作为前缀,而且axios请求接口的地址也以/api开头,则可以不用pathRewrite。
axios 使用
import axios from ‘axios‘ const testapi = {}; testapi.getFlights = function () { var result= {}; axios.defaults.baseURL = ‘/spider‘ axios.get(‘/api/ctrip/plan?deaprtureTime=2020-10-02&dcity=上海&acity=乌鲁木齐‘) .then(response => result = response.data) .catch(function (err) { console.error(err) }); return result } export default testapi
在vue.config.js中配置proxy(代理)
module.exports = { devServer: { proxy: { ‘/spider‘: { target: ‘http://localhost:5000‘, // 接口的地址 changeOrigin: true, // 允许改变源 pathRewrite: { ‘^/spider‘: ‘/‘ // 实际的接口地址没有这个,重写掉 } } } } }
实际使用
注意事项
原文:https://www.cnblogs.com/WattWang/p/vuestudy002.html