Today we are going to make a POST request using Reqres and Fetch API in JavaScript. We’ve previously seen how to make a GET request. But before we go straight to coding, let’s see what a POST request is.
What is a POST Request?
A POST request is one of the HTTP request methods used by web browsers and servers to send data to the server. When a client (typically a web browser) sends a POST request to a server, it includes data in the body of the request, which the server then processes. POST requests are often used for submitting data such as form inputs, file uploads, or any other data that needs to be processed by the server.
Here are some key points about POST requests:
- Data in the Body: Unlike GET requests, which include data in the URL, POST requests send data in the body of the request. This allows for larger amounts of data to be sent and doesn’t expose sensitive information in the URL.
- Security: POST requests are generally considered more secure for sending sensitive data, such as login credentials or payment information, because the data is not visible in the URL and is encrypted if using HTTPS.
- Idempotent: POST requests are not idempotent, meaning that multiple identical POST requests may have different effects on the server. For example, submitting a form twice may create two separate entries in a database.
- Usage: POST requests are commonly used for submitting HTML forms, uploading files, and performing actions that modify data on the server, such as creating, updating, or deleting resources in a RESTful API.
- Response: After processing the data sent in a POST request, the server typically responds with an appropriate HTTP status code to indicate the outcome of the request (e.g., 200 OK for success, 400 Bad Request for invalid input, etc.) and optionally returns data in the response body.
Next, we are going to create a form with an email and password inputs with Bootstrap for styling:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Form</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
Login
</div>
<div class="card-body">
<form>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<button id="submit" type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- Bootstrap JS and dependencies (jQuery, Popper.js) -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
Here’s what it looks like:
Next, we are going to post data to our endpoint: https://reqres.in/api/login
This is the request we are making:
{
"email": "eve.holt@reqres.in",
"password": "cityslicka"
}
And this is the response we are expecting:
{
"token": "QpwL5tke4Pnpja7X4"
}
So, we will get the values from our input using querySelector as follows:
<script type="text/javascript">
let email = document.querySelector("#email");
let password = document.querySelector("#password");
let button = document.querySelector("#submit");
button.addEventListener("click", ()=> {
alert(email.value);
})
</script>
So here we are getting the form values and alerting it for testing purposes:
Next, we will use Fetch API to consume our endpoint:
button.addEventListener("click", (e)=> {
e.preventDefault()
// Data to be sent in the request body (replace with your actual data)
const requestData = {
email: email.value,
password: password.value
};
// URL to which the request will be sent (replace with your actual URL)
const url = 'https://reqres.in/api/login';
// Fetch POST request
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json', // Specify content type as JSON
// You may need additional headers like Authorization if required by the server
},
body: JSON.stringify(requestData) // Convert data to JSON string
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // Parse response body as JSON
})
.then(data => {
// Handle successful response
console.log('Response:', data);
})
.catch(error => {
// Handle error
console.error('There was a problem with the fetch operation:', error);
});
})
A few explanation is necessary here:
- We’re using e.preventDefault() because we don’t want the page to refresh after submission. This is just for testing purpose.
- The request body is converted to JSON format using
JSON.stringify()
because the Content-Type header is set toapplication/json
. - The response is checked for errors using
response.ok
. If the response status is not in the range 200-299, an error is thrown. - You can handle the response data in the second
.then()
block or handle any errors in the.catch()
block.
So to test our endpoint, we need to pass the expected values which are believed to be in our database and also so we can simulate for a response:
{
"email": "eve.holt@reqres.in",
"password": "cityslicka"
}
Here’s the full code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Form</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
Login
</div>
<div class="card-body">
<form>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<button id="submit" type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
let email = document.querySelector("#email");
let password = document.querySelector("#password");
let button = document.querySelector("#submit");
button.addEventListener("click", (e)=> {
e.preventDefault()
// Data to be sent in the request body (replace with your actual data)
const requestData = {
email: email.value,
password: password.value
};
// URL to which the request will be sent (replace with your actual URL)
const url = 'https://reqres.in/api/login';
// Fetch POST request
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json', // Specify content type as JSON
// You may need additional headers like Authorization if required by the server
},
body: JSON.stringify(requestData) // Convert data to JSON string
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // Parse response body as JSON
})
.then(data => {
// Handle successful response
console.log('Response:', data);
})
.catch(error => {
// Handle error
console.error('There was a problem with the fetch operation:', error);
});
})
</script>
<!-- Bootstrap JS and dependencies (jQuery, Popper.js) -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
Here’s the result:
This is the token we’re getting on a successful login:
Conclusion
This is how to make a post request using Fetch API in JavaScript. Let me know what you think in the comments.