Reputation: 2527
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!
Upvotes: 7
Views: 2708
Reputation: 326
Nuxt provides a proxy option which you can use to avoid cors errors, Nuxt Documentation
You can refer this for more information and available options @nuxt/proxy
Upvotes: 1
Reputation: 3536
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",
},
});
Upvotes: 1