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!
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",
},
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With