【问题标题】:Access to XMLHttpRequest at 'http://localhost:8000/auth/users/me/' from origin 'http://localhost:3000' has been blocked by CORS policyCORS 策略已阻止从源“http://localhost:3000”访问“http://localhost:8000/auth/users/me/”处的 XMLHttpRequest
【发布时间】:2021-03-14 15:59:06
【问题描述】:

我在调用 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.

【问题讨论】:

  • 请帮帮我!!!!!!

标签: reactjs django-rest-framework


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2019-10-05
    • 2021-12-18
    • 2021-03-08
    • 2021-10-05
    • 1970-01-01
    • 2020-12-18
    • 2021-01-24
    • 1970-01-01
    • 2020-11-11
    相关资源
    最近更新 更多