So, I made a simple api request using Nuxt/SSR. I have cities and categories. Each city has a list of categories. To fetch cities I have to use https://api/cities and to get categories I should use https://api/cities?id
store/cities.js
export const state = () => ({
cities: [],
})
export const mutations = {
setCities(state, cities) {
state.cities = cities
},
}
export const actions = {
async fetch({ commit }) {
const cities = await this.$axios.$get(
'https://api/cities'
)
commit('setCities', cities)
},
}
export const getters = {
cities: (s) => s.cities,
}
And it works perfectly with this index.vue:
export default Vue.extend({
async fetch({ store }) {
if (store.getters['cities/cities'].length === 0) {
await store.dispatch('cities/fetch')
}
},
computed: {
cities() {
return this.$store.getters['cities/cities']
}
}
})
But now I want to fetch categories on click (to choose city ID):
store/categories.js
export const state = () => ({
categories: [],
})
export const mutations = {
setCategories(state, categories) {
state.categories = categories
},
}
export const actions = {
async fetch({ commit }, cityId) {
const categories = await this.$axios.$get(
'https://api/cities?id=' <data that I get on click>
)
commit('setCategories', categories)
},
}
export const getters = {
categories: (s) => s.categories,
}
And index.vue now:
export default Vue.extend({
computed: {
cityCategories() {
return []
},
},
methods: {
// this function I call on click
selectCity(selectedCityId) {
this.$store.dispatch('categories/fetch', selectedCityId)
}
}
})
But after this I get an error on click:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api/cities?id. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api/cities?id. (Reason: CORS request did not succeed). Status code: (null).
I'm sure the problem isn't in api, because I tried to fetch categories with 1st method without click (just edited id to 1) and it worked. I have the same local domain, so it's not about headers in api.
CodePudding user response:
CORS is definitely at the API.
Set the Access-Control-Allow-Origin
header on response from the back-end.
CodePudding user response:
It didn't work on click because it was a request from browser/localhost, not from nuxt server. So I just installed nuxtjs proxy to send a request on local server first.