【发布时间】:2022-01-04 01:42:31
【问题描述】:
我正在开发基于 MERN 的 Web 应用程序,但在让 ReactJS 将用户令牌保存到本地存储时遇到问题。它正确地向 MongoDB 发送数据并从 React UI 中取回令牌,但没有保存令牌。
这是形式:(我也在使用tailwind进行造型)
<form onSubmit={this.submitInfo} className="shadow-md rounded px-8 pt-6 pb-8 mb-4">
<div className="mb-4">
<label className="block text-gray-700 text-sm font-bold mb-2">
Username:
<input id="username" type="text" value={this.state.name} onChange={this.inputChange} className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"/>
</label>
</div>
<div className="mb-4">
<label className="block text-gray-700 text-sm font-bold mb-2">
Email:
<input id="email" className="shadow" type="email" value={this.state.email} onChange={this.inputChange} className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"/>
</label>
</div>
<div className="mb-4">
<label className="block text-gray-700 text-sm font-bold mb-2">
Password:
<input id="password" type="password" value={this.state.password} onChange={this.inputChange} className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"/>
</label>
</div>
<div className="flex items-center justify-between">
<input className="bg-primary hover:bg-highlight text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="submit" value="Signup"/>
</div>
</form>
这是单击提交按钮时运行的函数:
submitInfo(event){
fetch(`http://localhost:5000/users/register`, {
method: 'POST',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify({"userName":this.state.name, "email":this.state.email, "password":this.state.password})
})
.then(response => localStorage.setItem("token", JSON.stringify(response)))
.catch(err => console.error(err));
window.location.href = "/browse"
}
我看不出我的实现有什么本质上的错误。我已经用邮递员测试了 API,它发回了一个非常好的令牌,所以问题必须在反应方面。有什么我忽略的吗?
编辑: 我尝试删除窗口重定向,但仍然无法保存令牌。
【问题讨论】:
-
重定向将在 fetch 完成之前发生。您也没有阻止默认的表单提交过程
-
在
fetch得到响应之前尝试event.preventDefault();看看页面是否正在重定向。
标签: javascript html reactjs local-storage