这是我的React 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);
});
};
}
这是我的服务器配置(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",
]
所以我有后端错误:禁止(未设置CSRF cookie):/
请问这个问题是最新的,但是尝试的所有解决方案都无法解决我的问题...
答案 0 :(得分:0)
您需要在请求标头中添加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);
});
//下面的函数从cookie中返回csrftoken。
export const getCsrfToken = () => {
const csrf = document.cookie.match('(^|;)\\s*csrftoken\\s*=\\s*([^;]+)');
return csrf ? csrf.pop() : '';
};