I have an error on my Nuxt App and I don't understand why it not work. I have 2 files post_data.json and 0001.json in my server. The post_data.json work without any CORS issue, this is the index.vue page fetch :
async fetch() {
const type = 'post';
await this.$store.dispatch('getPostBy',type).then(()=> {
console.log("Got some data, now lets show something in this component")
}, error => {
console.error("Got nothing from server. Prompt user to check internet connection and try again", error)
})
},
in store :
async getPostBy ({ commit, state}, type) {
try {
let siteUrl = state.api_url;
let url = `${siteUrl}/${type}/${type}_list.json`;
const headers = {
"Content-Type": "application/json",
"Accept": "application/json",
};
await fetch(url, {
method: "GET",
headers,
})
.then(data => data.json())
.then(response=>{
commit('SET_POSTS', response) // Save Item in Store
})
.catch( e=> {
console.log("getPostBy 3. OUTSIDE 401 ", e);
});
} catch (e) {
}
},
Instead, when I navigate to single post, i get this error :
Access to fetch at 'http://www.example.com/post/0001.json' from origin 'http://localhost:8010' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
This is the code of asyncData :
asyncData({app, route, store}) {
const id = route.query.p;
const category = 'post';
try {
let siteUrl = 'http://www.example.com';
let url = `${siteUrl}/${category}/${id}.json`;
const headers = {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
"Accept": "application/json",
};
fetch(url, {
method: "GET",
//mode: "no-cors",
headers,
})
.then(data => data.json())
.then(response=>{
console.log("response", response)
let item = response;
store.dispatch("updateItem", {item})
})
.catch( e=> {
console.log("asyncData error ", e);
});
} catch (e) {
}
},
If i open the file in browser or if I reload the page, i will see the content of json file, instead if I change route I get the CORS error. I tryed to add "Access-Control-Allow-Origin": "*" and also mode: "no-cors", but i still have the issue.