我正在使用React,Redux和django rest api来构建一个简单的网站,目前正在学习使用django-rest-auth,除了注销之外,一切都很好,这会给我一个CSRF失败的错误。
auth.js
export const logout = token => {
localStorage.removeItem('expirationDate');
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json",
'X-CSRFToken':token,
},
};
fetch("/rest-auth/logout/", requestOptions)
return {
type: actionTypes.AUTH_LOGOUT
};
}
export const authLogin = (username, password) => {
return dispatch => {
dispatch(authStart());
axios.post('http://127.0.0.1:8000/rest-auth/login/', {
username: username,
password: password
})
.then(res => {
const token = res.data.key;
const expirationDate = new Date(new Date().getTime() + 3600 * 1000);
localStorage.setItem('token', token);
localStorage.setItem('expirationDate', expirationDate);
dispatch(authSuccess(token));
dispatch(checkAuthTimeout(3600));
})
.catch(err => {
dispatch(authFail(err))
})
}
}settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
}发布于 2021-04-14 21:31:07
解决方案是为axios设置缺省标头
auth.js
axios.defaults.xsrfHeaderName = "X-CSRFToken";
axios.defaults.withCredentials = true
export const logout = () => {
localStorage.removeItem('token');
axios.post("/rest-auth/logout/", {})
return {
type: actionTypes.AUTH_LOGOUT
};
}settings.py
CSRF_COOKIE_NAME = "XSRF-TOKEN"https://stackoverflow.com/questions/67090412
复制相似问题