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:

Chrome:

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.
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.
pip install django-cors-headers
Then allowed it in the settings.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:

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?
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