我正在处理一个用户登录项目。我的前端是React,服务器端是Node / Express js。我正在尝试了解JWT来创建受保护的路由。但是,在将我的令牌(已经成功生成)发送回我的前端应用程序时,我陷入了困境。我试图将令牌存储在cookie中,然后将其发送回我的反应端。我的理解是,在访问服务器端的受保护路由之前,必须将令牌存储在React端,但是我对如何进行此操作感到困惑。这是我的服务器上登录请求的代码:
app.post('/userLogin', function(req, res) {
var {usernameLogin, passwordLogin} = req.query;
console.log(req.query);
var validateLogin = `SELECT CustomerID FROM CUSTOMER WHERE Username='${usernameLogin}' AND Password='${passwordLogin}'`;
mysqlConnection.query(validateLogin, (error, result) => {
if(error) {
console.log(error);
} else {
// Checks to see if the result object (CustomerID) exists or not.
if(Object.entries(result).length === 0) {
console.log('sorry');
} else {
console.log(result);
console.log('existing');
const token = jwt.sign({ usernameLogin: usernameLogin}, 'loginKey');
res.cookie('token', token, { httpOnly: true}).sendStatus(200);
console.log(token);
}
}
});
});
这是我的React应用程序中的我的react onSubmit(称为登录)。就像一个旁注,“成功”消息已成功打印到控制台,但这是我不知道如何在客户端检索和存储令牌以供将来访问受保护的路由的地方:< / p>
login = (event) => {
event.preventDefault();
console.log(this.state);
fetch('http://localhost:3001/userLogin?usernameLogin=' + this.state.usernameLogin +
'&passwordLogin=' + this.state.passwordLogin, {method: 'POST'}
)
.then(res => {
if (res.status === 200) {
console.log("it worked!!!");
} else {
console.log('there was a problem at line 27');
}
})
};
任何见识将不胜感激!!!
答案 0 :(得分:0)
对于客户端,您可以使用 localStorage 属性存储从服务器端返回的令牌。
设置项目的示例:localStorage.setItem("token", <token>);
获取项目的示例:let token = localStorage.getItem("token");
文档:https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Local_storage
PS:让我知道是否足以解决您的问题。
答案 1 :(得分:0)
只需使用localStorage将其保存在本地即可。
服务器端
// Using JSON ease the client-side access
res.status(200).json({ token: token, status: 200 });
客户端
fetch('your-api-endpoint')
.then((res) => res.json())
.then((res) => {
if (res.status === 200) {
localStorage.setItem('token', res.token);
} else {
// TODO: handle the error
}
});
// Later, when you need the claim to access protected routes
const token = localStorage.getItem('token');