I'm working on an MERN based web application and I'm having issues getting ReactJS to save a user token into local storage. It correctly sends data to MongoDB and gets the token back from the React UI but isn't saving the token.
This is the form: (I'm also using tailwind for styling)
<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> This is the function that runs when the submit button is clicked:
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" } I cant see anything inherently wrong about my implementation. I've tested the API with postman and it sends back a token perfectly fine so the issue must be on the react side. Is there something I'm overlooking?
EDIT: I tried removing the window redirect and its still unable to save the token.
event.preventDefault();to see if the page is redirecting beforefetchgets a response.