[英]React requests with axios on DRF api throws error Forbidden (CSRF cookie not set.)
This is my react Js code : 这是我的反应Js代码:
export function loginUser({ email, password }, history) {
return (dispatch) => {
axios({
url: URL_LOGIN_BASE,
method: "POST",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
// withCredentials: true,
data: { "email": email, "password": password }
}).then(response => {
dispatch(setAuthentification(true));
history.push("/dashboard");
console.log(response);
}).catch(err => {
console.log(err);
});
};
}
And here my the server configuration (settings.py): 这是我的服务器配置(settings.py):
ALLOWED_HOSTS = [
"127.0.0.1",
"localhost",
"192.168.0.1",
"mockbic.spnnjy4rjm.eu-west-3.elasticbeanstalk.com"
]
CORS_ORIGIN_WHITELIST = (
'localhost:3000',
'127.0.0.1:3000',
)
CORS_ALLOW_HEADERS = (
'accept',
'accept-encoding',
'Access-Control-Allow-Origin',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
'mock-bic-token', # IMPORTANT
)
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"storages",
"datacollection.apps.DatacollectionConfig",
"corsheaders",
]
So i have the backend error : Forbidden (CSRF cookie not set.): / 所以我有后端错误:禁止(未设置CSRF cookie。):/
Please this question is very current but all solutions tried don't resolve my case... Help ! 请问这个问题是最新的,但是所有尝试的解决方案都不能解决我的问题。
you need to add csrf
token in your request headers. 您需要在请求标头中添加csrf
令牌。
export function loginUser({ email, password }, history) {
return (dispatch) => {
axios({
url: URL_LOGIN_BASE,
method: "POST",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"X-CSRFToken" : "TOKEN FROM YOUR COOKIES"
},
// withCredentials: true,
data: { "email": email, "password": password }
}).then(response => {
dispatch(setAuthentification(true));
history.push("/dashboard");
console.log(response);
}).catch(err => {
console.log(err);
});
// function below returns csrftoken from cookies. //下面的函数从cookie返回csrftoken。
export const getCsrfToken = () => {
const csrf = document.cookie.match('(^|;)\\s*csrftoken\\s*=\\s*([^;]+)');
return csrf ? csrf.pop() : '';
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.