首页 > 解决方案 > 从源“http://localhost:3000”访问“http://localhost:8000/auth/users/me/”的 XMLHttpRequest 已被 CORS 策略阻止

问题描述

我在调用 get api http://localhost:8000/auth/users/me/(django djoser simplejwt) 时遇到问题,发生了 cors 阻塞问题。无法获取任何数据并且发生 api 错误。

我的反应前端是这样的

export const fetchUser  = () => {
console.log(localStorage.getItem('token'))
const config = {

    headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`,
        "Access-Control-Allow-Origin" : "",
        "Allow": "GET",
        "Content-type": "Application/json",

    
    }
};
debugger

return dispatch => {
    // dispatch(fetchUser());
    // debugger
    axios.get(`${process.env.REACT_APP_API_URL}/auth/users/me/`,config)
        .then(response => {
            dispatch({
                type:USER_SUCCESS ,
                payload: response.data
            });
        })
        .catch(error => {
            dispatch(userFailure(error));
        });
};

};

和这样的错误。这只发生在我使用get方法时

Access to XMLHttpRequest at 'http://localhost:8000/auth/users/me/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
    xhr.js:177 GET http://localhost:8000/auth/users/me/ 

my backend is fixed with all cors settings
INSTALLED_APPS = ["'corsheaders',]

MIDDLEWARE = ['corsheaders.middleware.CorsMiddleware',]

CORS_ORIGIN_ALLOW_ALL = True

and also used whitelist allow.

标签: reactjsdjango-rest-framework

解决方案


如果您想允许所有来源,那么您的后端需要OPTIONS使用标头响应预检请求Access-Control-Allow-Origin: *

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin


推荐阅读