reactjs - 登录后未使用 Fetch 存储的 Cookie
问题描述
我正在使用 REST api 将 React 作为前端,将 Drupal 作为后端来实现身份验证。
从我正在使用的fetch
函数中获取数据;登录我/user/login?_format=json
从 Drupal 向端点发送请求,结果我得到:uid、name、csrf_token 和 logout_token。
响应消息OK,因为我正确接收到数据,但是cookie没有存储在浏览器中,数据只存储在本地存储中。
我怀疑这会导致一些问题,因为当我提出其他一些请求时,我得到了401 error
. 此外,当触发注销端点(/user/logout?_format=json&token=logout_token
)时,我得到403 error
.
这是代码:
const submitData = async event => {
event.preventDefault();
if(captcha == null) {
setErrorMessage("You did not check the CAPTCHA");
} else if(username == null || pass == null) {
setErrorMessage("You did not fill all the necessary fields");
} else {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("withCredentials", true);
myHeaders.append("Access-Control-Allow-Origin", "*");
var raw = JSON.stringify({
name: String(username),
pass: String(pass)
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
credentials: "same-origin",
};
await fetch(
process.env.REACT_APP_API_HOST +"/user/login?_format=json",
requestOptions
)
.then((response) => response.text())
.then((result) => {
if (JSON.parse(result).current_user){
window.localStorage.setItem("user-info", result);
window.location.replace("/registration-landing");
} else {
setErrorMessage("An error occured. "+JSON.parse(result).message);
}
})
.catch((error) => console.log("error", error));
}
我究竟做错了什么?我应该使用axios
而不是fetch
吗?
解决方案
推荐阅读
- php - 从 HTTP 重定向到 HTTPS(最好的方法是 .htaccess 或 PHP 重定向代码)
- java - 如何在 AWS ElasticBeastalk Application Load Balancer 上运行的 Spring webapp 上获取请求者 IP
- c++ - 将 OpenBLAS 包含和库搜索路径链接到 CMake for OpenCV
- python - 迭代数据帧并用另一个数据帧中的值替换
- mysql - mysqldump 抛出“拒绝访问”错误,但仅在通过 logrotate 运行时?
- c# - 如何进行空比较以返回false
- c++ - 当 A 类没有默认构造函数时,在 B 类中有一个 A 类
- python - 使用 matplotlib 删除时间历史图中的垂直线
- garbage-collection - gc log是minor gc还是full gc
- html - 如何使祖父div的子div绝对如下结构?