javascript - Fetch API 未发送 Cookie
问题描述
我已经用 Node.js 实现了一个登录系统,它在成功验证后在客户端浏览器中放置一个 cookie。此 cookie 包含稍后从数据库中获取客户端信息所需的客户端用户名,我正在尝试使用 Fetch API 请求将该 cookie 发送到我的节点服务器,然后在服务器端读取用户名,但这会返回undefined
。这是我的登录系统:
var cookie_parser = require('cookie-parser');
app.use(cookie_parser('mysecretkey'));
app.post('/login', function(req, res) {
var loginCredentials = {
Email: req.body.email,
Password: req.body.password,
}
loginCredentials.Password = hashPassword(loginCredentials.Password);
console.log(loginCredentials);
CheckPassword(loginCredentials, returnResult);
// Function used by login API method to fetch password hash by email address from database
function CheckPassword(loginCredentials, callback) {
con.query("SELECT Password FROM Customers WHERE Email =?", loginCredentials.Email, function(err, result) {
if (!err) {
callback(false, result);
} else {
callback(true, err);
}
})
}
// Function for returning the login result
// if login is successful, redirect user to front page
function returnResult(error, result) {
if (error) {
res.send(`Database error: ${result}`);
} else {
if (result.length > 0 && loginCredentials.Password == result[0].Password) {
res.cookie('user', loginCredentials.Email, {signed: true});
res.redirect("http://localhost:3000/");
} else {
res.send("Login failed: incorrect email or password");
}
}
}
});
然后我试图从那个cookie中读取用户名:
app.get('/getCustomerInfo', function (req, res) {
var username = req.signedCookies.user;
console.log(username); // prints undefined
if (username == undefined) {
res.send('You are not logged in. Log in to place the order');
} else {
con.query("SELECT FirstName, LastName, Address, Email, Phone FROM Customers WHERE Email =?", username, function(err, result) {
if (!err) {
console.log(result);
res.send(result);
} else {
console.log(err);
}
});
}
});
这是我的 Fetch API 请求:
function GetCustomerInfo() {
fetch(`http://127.0.0.1:5000/getCustomerInfo`, {
method: 'GET',
credentials: 'include'
})
.then((response) => response.json())
.then((response) => {
setCustomerInfo(response);
})
.catch((error) => {
console.error(error);
});
return (
<div>
<h2>
{customerInfo}
</h2>
</div>
);
}
我究竟做错了什么?任何建议将不胜感激。
解决方案
推荐阅读
- go - 在 golang 中全局设置时区
- java - 在另一个包的主包中使用一个包中的 java 类(同一项目)
- publish - 无法发布 G Suite Marketplace 插件
- elasticsearch - Elasticsearch - 为将来的索引配置 index.mapping.total_fields.limit
- html - 如何更改materializecss中列的断点顺序?
- java - Grails 脚手架视图中没有水平滚动
- javascript - 我的列表过滤器不会隐藏所有内容
- amazon-web-services - 如何在不重建 lambda 的情况下更新现有 AWS-lambda 触发器或其 cft?
- lucene - 使用 Kibana 进行弹性查询
- excel - VBA - 如何选择包含特定单元格的列并将其命名为输出列?