Sometimes, we want to make a POST request with Fetch API and JavaScript.
In this article, we’ll look at how to make a POST request with Fetch API and JavaScript.
How to make a POST request with Fetch API and JavaScript?
To make a POST request with Fetch API and JavaScript, we call fetch with the method option set to 'post'.
For instance, we write
const res = await fetch("http://example.com/api/endpoint/", {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
name,
password,
}),
});
to call fetch with the URL to make the request to and an object with some request options.
In the object, we set method to 'post' to make a post request.
We set headers to an object with the request headers keys and values.
And we set body to a JSON string with the request body.
Conclusion
To make a POST request with Fetch API and JavaScript, we call fetch with the method option set to 'post'.