0

My server (written with Django) is running at http://localhost:8000.

The Nuxt application is running at http://localhost:3000.

When I send a request (like http://localhost:8000/api/v1/user/position/) to the server, I get the following error in the firefox browser.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/v1/user/position/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Firefox:

error in firefox network tab

Chrome:

Error in chrome network tab

I saw this link and this but I do not know where the problem comes from?

Below is a section of my nuxt.config.js file.

modules: [
    '@nuxtjs/axios',
    '@nuxtjs/proxy'
],
axios: {
    baseURL: 'http://localhost:8000/api/v1/', 
},

And function that I'm sending a request:

async getAllPosition() {
    this.loading_position = true;
    await this.$axios.get('user/position/').then(response => {
          this.position = response.data;
    }).finally(() => {
         this.loading_position = false;
        })
 }

I think it's about proxy, but i don't know how to config it.

TMFLGR
  • 158
  • 1
  • 10
Saeed
  • 2,594
  • 2
  • 21
  • 36

4 Answers4

2

As @BananaLama and @TMFLGR mentioned in their answers:

I need to specify Access-Control-Allow-Origin header in my Django server to allow request across origins. For this purpose, I used django-cors-headers package and allowed it in the seetings.py section and the results were well returned.

// settings.py

INSTALLED_APPS = [
    ...
    'corsheaders',
]

MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

CORS_ALLOWED_ORIGINS  = [
    "http://localhost:3000",
]

Result:

enter image description here

Saeed
  • 2,594
  • 2
  • 21
  • 36
1

As the error message reveals: You need to specify a Access-Control-Allow-Origin-header in your Server to allow your request across origins. (yea ::3000 and ::8000 are different origins). Modern Browsers will fire a options (pre-flight) request to check the Access-* headers when requesting another origin. You must answer those OPTIONS requests with at least a Access-Control header. Access-Control-Allow-Origin: localhost:3000 should be fine for development.

More about CORS and the Browser OPTIONS Request here:
https://enable-cors.org/
Why is an OPTIONS request sent and can I disable it?

TMFLGR
  • 158
  • 1
  • 10
1

You can set up a forward proxy to handle cross-domain

nuxt.config.js:


export default {
  ...
  proxy: {
    '/api': { 
      target: 'http://localhost:8000',
      pathRewrite: {
        '^/api': '/api',
        changeOrigin: true
      }    
    }
  },
}
linchong
  • 369
  • 1
  • 4
1

As @TMFLGR mentioned: Add a OPTION-Request handler to your server and specify a Access-Control-Allow-Origin Header. Proxy is fine for development but in production you should not do this.

BananaLama
  • 21
  • 4