Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix vue axios CORS issue?

Tags:

vue.js

How can I prevent CORS issue with vue axios?

Following is the code for making requests with the backend using vue and axios.

axios.config.js

/// here I'm creating a vue axios instance.

import axios from "axios";

export default axios.create({
  baseURL: "https://example.com/api/v1/",
  headers: {
    Accept: "application/json",
    Authorization: "TOKEN 3413413dfdsfsafd3rr41",
  },

});

and inside the vue.config.js

I've proxied the request.

module.exports = {
  devServer: {
    proxy: {
      "/api/*": {
        target: "http://localhost:8081",
        secure: false,
        changeOrigin: true,
      },
    },
  },
};


and inside my vuex store I'm calling an action:

import axios from 'axios.config'

  actions: {
    getData({ commit }) {
      axios
        .get(`products/grocery`)
        .then((res) => {
          console.log("res :", res);
          commit("SET_DATA", res.data);
        })
        .catch((e) => {
          console.log("e :", e);
          commit("SET_ERROR", e);
        });
    },
}

But when I look at the request in the console, I can see that it is sending request to the original url https://example.com/api/v1/ rather than appending the dev server line this: http://localhost:8081/api/v1/

Not sure why the proxying is not working!

like image 749
mx_code Avatar asked Nov 15 '22 03:11

mx_code


1 Answers

External URLs doesn't get proxied. Change the base URL in axios to /api/v1/

export default axios.create({
  baseURL: "/api/v1/",
  headers: {
    Accept: "application/json",
    Authorization: "TOKEN 3413413dfdsfsafd3rr41",
  },
});
like image 68
MjZac Avatar answered Jun 25 '23 04:06

MjZac