[英]403 Forbidden Error when trying to post and put a axios request in a web app using Django and React
[英]403 Forbidden request when making an axios call with React (Django backend)
我正在嘗試使用 ReactJS 在 web 應用程序上驗證我的 session。我的后端設置在 Django 上。登錄到應用程序時,我確實在 cookies 中收到 cookies,但是當 I6819 無法設置時嘗試發布請求“withCredentials:true”,它返回 403 錯誤。
登錄調用(我在響應標頭中收到 cookies)
let url = `${BASE_URL}/login/`;
console.log('params for validateOtp:', params);
axios
.post(url, params)
.then((res) => {
console.log('validate otp code res: ', res);
resolve(res);
})
.catch((err) => {
console.log('validate otp code err: ', err);
reject(err);
});
查看控制台后,在“網絡”選項卡下可以看到我確實從這個 API 收到了 cookies。
這是我進行身份驗證調用的 API。
let url = `${BASE_URL}/updatemerchant/`;
axios
.post(url, params, {
withCredentials: true
}
)
.then((res) => {
console.log('updateDukaanUserToCloud res : ', res);
// resolve(res)
if (res.status === 200) {
resolve(res);
} else {
reject('updateDukaanUserToCloud something went wrong');
}
})
.catch((err) => {
if (err.response && err.response.status === 400) {
reject('updateDukaanUserToCloud updating user info failed');
} else {
reject('updateDukaanUserToCloud something went wrong');
}
});
設置.py
CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOW_CREDENTIALS = True
CSRF_COOKIE_NAME = "csrftoken"
CORS_ORIGIN_WHITELIST = ('http://localhost:3000', 'http://127.0.0.1:3000', 'localhost:3000', '127.0.0.1:3000')
CSRF_TRUSTED_ORIGINS = [
'localhost:3000',
'127.0.0.1:3000',
]
到目前為止,CSRF 令牌應該不是問題,因為您無法通過身份驗證問題。 如果正確安裝了 Django “會話身份驗證”,只要從 React 傳遞了正確的憑據,並且在 Django 中調用了“登錄”方法,它應該會自動附加 session cookie,您不需要在 React 中做額外的工作。
您是否添加了“django.contrib.sessions.middleware.SessionMiddleware”中間件?
PS 如果以后要使用 POST 請求,則需要附加 CSRF Token。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.