Vue跨域请求,前端配置

2020-02-13  本文已影响0人  木头就是我呀

在vue-cli生成的项目中,使用axios跨域请求时,会报错,前端解决方案配置如下:

module.exports = {
    publicPath: './',
    devServer: {
        open: true, //浏览器自动打开页面
        host: "localhost", //如果是真机测试,就使用这个IP
        port: 8080,
        https: false,
        hotOnly: false, //热更新(webpack已实现了,这里false即可)
        proxy: {
            //配置跨域-将所有/api的请求拦截,代理到target上
            '/api': {
                target: "http://yangxc.cn:7001/test-api",
                ws:true,
                changOrigin:true,
                pathRewrite:{ //---->>>并将/api换成/
                    '^/api':'/' 
                }
            }
        }
    }
}
import Vue from 'vue'
import App from './App.vue'
import Axios from 'axios'

// 引入vant
import Vant from 'vant'
import 'vant/lib/index.css'

Vue.use(Vant);

Vue.config.productionTip = false
Vue.prototype.$axios = Axios
Axios.defaults.baseURL = '/api' // <<<<<<<------此处将所有经过axios的请求加上了/api
Axios.defaults.headers.post['Content-Type'] = 'application/json';


import router from "./router"

new Vue({
  render: h => h(App),
  router,
}).$mount('#app')
上一篇 下一篇

猜你喜欢

热点阅读