![](/img/trans.png)
[英]Request header field … is not allowed by Access-Control-Allow-Headers in preflight response
[英]blocked by CORS policy: Request header field access-control-allow-methods is not allowed by Access-Control-Allow-Headers in preflight response
async onSubmit(e) {
e.preventDefault();
axios.post('http://127.0.0.1:8000/auth/token/login',{
email:this.state.email,
password:this.state.password,
}).then(res => {
localStorage.setItem('token', JSON.stringify(res.data));
this.props.history.push('/protcted')
});
console.log("resgister!");
// console.log(resd.json());
}
异步组件DidMount() {
if (!this.state.logged_in) {
this.props.history.push('./login')
}
console.log(user));
if (this.state.logged_in) {
fetch('http://localhost:8000/auth/users/me', {
method: 'GET',
headers: {
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type,
Accept, Authorization",
"Access-Control-Allow-Methods": "*",
"Authorization": `Token ${localStorage.getItem('token')}`,
"Content-Type": 'application/x-www-form-urlencoded',
"withCredentials": true,
"Access-Control-Allow-Origin":"*",
'X-Requested-With': 'XMLHttpRequest'
}
})
.then(res => JSON.stringify(res.data))
.then(json => {
this.setState({ username: json.username });
});
}
}
设置.py
INSTALLED_APPS = [
'authapp',
'rest_framework',
'djoser',
'rest_framework.authtoken',
'corsheaders',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
注册完成工作此本地主机 URL 但无法登录。在此 onSubmit 方法中,完全工作令牌确实存储在 localStorage 中,但我尝试使用此令牌进行身份验证,但出现此错误。
令人惊讶的是我在 Postman 中请求 http://localhost:8000/auth/users/me 这个 URL 然后我得到数据
您可以在给定链接中看到这张照片
django-cors-headers
中允许的标头的默认列表不包括access-control-allow-headers
。
Access-Control-Allow-Origin
、 Access-Control-Expose-Headers
、 Access-Control-Max-Age
、 Access-Control-Allow-Credentials
、 Access-Control-Allow-Methods
和Access-Control-Allow-Headers
是HTTP可以为访问控制请求发回的标头。
请求应该没有它们。 此外, credentials
选项应配置为其自己的fetch
init 选项中的条目,以允许将 cookies 发送到其他域。
headers: {
"Authorization": `Token ${localStorage.getItem('token')}`,
"Content-Type": 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
},
credentials: 'include'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.