Post Request Using Fetch API for Simple Login Page

Let’s say we finished building a layout for a login page with necessary functions and it is ready to send login data to the server and get a response for authentication and authorization. If the login information is correct, it can proceed to the main page, or it can alert a message that the login information needs to be checked again. I had the first time to work with a back-end classmate to realize this process.
<form className=”login-form”>
<input
className=”login-info”
onChange={this.handleIdInput}
id=”id”
type=”text”
placeholder=”Phone number, username or email”
/>
<input
className=”login-info”
onChange={this.handlePwInput}
id=”password”
type=”password”
placeholder="Password" />
<button
className=”login-button”
disabled={this.enableLoginButton()}
id={this.changeLoginButtonStyle()}
type=”submit”
onClick={this.clickLogin}>
Login
</button>
</form>
- Refer to the code above for the login form. Note we have
this.handleIdInput
andthis.handlePwInput
toonChange
which set states for the values of id and password based on what a user enters. - Once the two states are set, the user would click the Login button. This is where the
this.clickLogin
will be executed. Let’s see it in detail below:
clickLogin = (e) => {
e.preventDefault();
fetch (“API Address", {
method: “POST”,
body: JSON.stringify({
email: this.state.idValue,
password: this.state.pwValue
}),
})
.then((response) => response.json())
.then((result) => {
if(result.message === “SUCCESS”){
alert(“You are logged in.”);
this.goToMain();
} else {
alert(“Please check your login information.”);
}
});
}
- Firstly, I have
e.preventDefault()
to prevent refreshing the whole page every time the button is clicked, because I found that when we useinput
orbutton
tags with a type likesubmit
, it reloads the whole page once the event, click in this case, happens. - Then, I wrote
fetch()
function that takes two parameters, the API address that you would get from the back-end side, and the object that has themethod
andbody
properties. We specify what method we are requesting (GET, POST, DELETE and so on) to the keymethod
. - for the
body
, we assign an object with keys that represent the information the server needs. The key names (email
,password
) are agreed on by both the front and back-end. The values to the keys are from thestates
that I set from theonChange
functions mentioned in the first section. NoteJSON.stringify()
which means we are sending the information in a string form to the server. fetch()
returns a promise. Here we need.then()
and specify what to do with the response.json()
takes the body text as JSON and returns a JavaScript object which can be an object, array, string and so on.- The second
.then()
handles the result we have from the response. I addedif
statement to check if the message of result is ‘SUCCESS’, it returns “You are logged in.” and then go to the main page. Else, it returns an alert message to check the login information again.