问题
I am trying to make a GET request in my application that is being served locally (port 8080) using on a node server. I am using Axios to make the request to a django REST server that is also being served locally (port 8000).
My request looks like:
axios.get('http://127.0.0.1:8000/recipes/',{headers: {"Access-Control-Allow-Origin": "*"}})
On the Django side, I've included these in my middleware
MIDDLEWARE = [
'django.middleware.common.CommonMiddleware',
'corsheaders.middleware.CorsMiddleware',
]
and this in my installed apps:
INSTALLED_APPS = [
'corsheaders',
]
And included this setting:
CORS_ORIGIN_ALLOW_ALL = True
But I'm still getting a CORS error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/recipes/. (Reason: missing token ‘access-control-allow-origin’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).
Any idea what I'm missing?
回答1:
I figured it out.
I needed to remove:
{headers: {"Access-Control-Allow-Origin": "*"}
from the request. Apparently that header should only be part of the response.
After removing, everything is working.
回答2:
You need to create an axios instance, putting the domain part of your url in baseUrl, and the rest in get, is that simple.
var instance = axios.create({
baseURL: "http://localhost:8088"
});
instance.get(url)
.then(function(response) {
})
来源:https://stackoverflow.com/questions/53577134/cross-origin-request-blocked-using-axios-and-django-rest