关于vue2和vue3的axios跨域问题

第一步

  npm install axios vue-axios --save; (安装对应的依赖)

第二步  (在main.js里面)

import axios from "axios";

import VueAxios from "vue-axios";

Vue.use(VueAxios, axios)
Vue.prototype.$axios = axios

第三部

  找到config文件下的index.js,在index.js里面找到module.exports 下的dev里面的proxyTable(如果没有需要自己添加)设置代码,如下:

  

proxyTable: {
      "/api":{ //这个是写死的(对应自己的)
        target:"http://localhost:8081/api", //这个是我后台接口的地址
        changeOrigin: true, 允许跨域
        pathRewrite: {
          "^/api":""  //以什么开头
        }
      }
    },

最后一步

  发送请求

this.$axios.get("/api/food/index").then(res=>{
        console.log(res.data)
})

 上面为vue2的

而vue3因为没有文件config所以可以通过在根目录里面新建一个vue.config.js文件,进行相关设置

大概是这样的

module.exports = {
  devServer: {
    open:false,
    proxy:{
      "/api":{
        target:"http://localhost:8081/api",
        ws:true,
        changeOrigin: true,
        pathRewrite: {
          "^/api":""
        }
      }
    }
  }
}

然后分享一下在跨域问题上踩得的两个坑

第一个

  mockjs和后端接口是冲突的   如果后台接口和mock同时使用的话会出现Error: Request failed with status code 404这个错误 (虽然你的跨域配置已经配置好了)    遇到这个注释掉mockjs相关代码就行

第二个

  当     target:"http://localhost:8081/api",这里已经写你的后端接口大概地址的时候不要再设置baseURL(也就是默认的请求地址  那样也会显示跨域没有配置好) 同样的进行空赋值就行

------------------------------------------------------------------

过了很久    踩的第三个坑   当按照相关配置进行跨域请求后 突然没有跨域问题  而是请求404     这里是因为(猜测可能是因为npm模块的问题)解决方法就是  在命令行里面 输入npm install  就行了

 

另外附上对应的个人代码    需要请求的地址为    http://localhost:8081/api/food/index

network/index.js

import axios from "axios"
export function users_data(config) {
    const instance = new axios.create({
      baseURL:"",
      timeout:5000,
      // headers:{"Content-Type":"application/x-www-form-urlencoded;;charset=utf-8"}
    });
  
    // 请求拦截器
    instance.interceptors.request.use(config => {
  
      let token = localStorage.getItem('token');
      if (token) {
        // 设置请求头中token的参数
        config.headers.common['token'] = localStorage.getItem('token');
        console.log(token)
      }
      //拦截后需要将拦截下来的请求数据返回发送
      return config;
  
    }, err => {
  
    })
  
    // 响应拦截器
    instance.interceptors.response.use(res => {
      // 拦截后需要将拦截下来处理成的结果返回
      return res.data
    }, err => {
      return Promise.reject(err)
    })
  
    return instance(config)
  }

network/home.js

import {users_data}from "./index"
export function getHomeData () { 
    return users_data({
        url:"/api/food/index"
    })
 }

vue.config.js

module.exports = {
    devServer: {
        open:false,
        host:"localhost",
        proxy:{
          "/api":{
            target:"http://localhost:8081/api",
            ws:true,
            changeOrigin: true,
            pathRewrite: {
              "^/api":""
            }
          }
        }
      },
}

 

posted @ 2021-02-27 13:02  熊灬火火  阅读(334)  评论(0)    收藏  举报