简体   繁体   中英

How to get rid of CORS error in Nuxt/SSR?

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

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 :完美配合:

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):

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 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).

, because I tried to fetch categories with 1st method without click (just edited id to 1) and it worked.,因为我试图在不单击的情况下使用第一种方法获取类别(只是将 id 编辑为 1)并且它有效。 I have the same local domain, so it's not about headers in api.

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.

CORS is definitely at the API.

Set the Access-Control-Allow-Origin header on response from the back-end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM