reactjs - 从源“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.
解决方案
如果您想允许所有来源,那么您的后端需要OPTIONS
使用标头响应预检请求Access-Control-Allow-Origin: *
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
推荐阅读
- javascript - 使用内容恢复 GridstackJS 面板(例如 Highcharts)
- c# - 突然无法更改 HttpClient 上的超时
- javascript - 未捕获的语法错误:构建后出现意外的令牌“<”(Vue.js)
- android - 显示带有 recyclerview 和改造的图像
- ionic4 - 在 ionic 4 中网络离线时显示模式
- java - 如何拆分但不是所有字符
- php - 卷曲不启用 wamp
- python - 仅定义变量后无法访问对象宏中的变量(rivescript)
- symfony - Symfony 3:如何使用 Collection 并验证它
- javascript - 获取嵌套对象键作为连接字符串