Question: Question In the below code I have written a simple user login page using React. Also, I have created my own backend using Express JS

Question

In the below code I have written a simple user login page using React. Also, I have created my own backend using Express JS + NodeJS and connected with MongoDB . From the frontend I am trying to authenticate user via http://localhost:5000/api/users. In the console I am getting this output after submitting the form index.js:28 POST http://localhost:5000/api/users 400 (Bad Request). Can someone correct the errors in this code? Thank you!

import React, { useState } from "react";

import {

Container,

Form,

FormButton,

FormContent,

FormH1,

FormInput,

FormLabel,

FormWrap,

Icon,

Text,

} from "./SigninElements";

const SignIn = () => {

const [email, setEmail] = useState("");

const [password, setPassword] = useState("");

const handleEmailChange = (e) => {

setEmail(e.target.value);

};

const handlePasswordChange = (e) => {

setPassword(e.target.value);

};

const handleSubmit = (e) => {

e.preventDefault();

fetch("http://localhost:5000/api/users", {

method: "POST",

body: JSON.stringify({

email: `"${email}"`,

password: `"${password}"`,

}),

headers: {

"Content-Type": "application/json",

},

})

.then((res) => {

if (res.status === 200) {

console.log("Login Success");

} else {

const error = new Error(res.error);

throw error;

}

})

.catch((err) => {

console.error(err);

alert("Error logging in please try again");

});

e.target.email.value = "";

e.target.password.value = "";

};

return (

to="/">Sushi Finder

action="POST" onSubmit={handleSubmit}>

Sign in to your account

htmlFor="for">Email

type="email"

required

onChange={handleEmailChange}

id="email"

/>

htmlFor="for">Password

type="password"

required

onChange={handlePasswordChange}

id="password"

/>

type="submit">Continue

Forgot Password

);

};

export default SignIn;

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!