DEV Community

Emmanuelthadev
Emmanuelthadev

Posted on

How to make a POST request in JavaScript

To make an HTTP POST request in JavaScript, we can use the XMLHttpRequest object or the fetch() function.

Here is an example of using XMLHttpRequest to make a POST request:

`function postData(url, data) {
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();

// Set the HTTP method to POST, the URL to the provided URL, and set the async flag to true
xhr.open("POST", url, true);

// Set the request header
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

// Send the request
xhr.send(data);
}`

You can call this function like this:
`postData("http://example.com/api/create_user", "name=Lennon&email=lennon@example.com");
Here is an example of using fetch() to make a POST request:

fetch('http://example.com/api/create_user', {
method: 'POST',
body: JSON.stringify({name: 'Lennon', email: 'lennon@example.com'}),
headers: {
'Content-Type': 'application/json'
}
}).then(response => response.json())
.then(data => console.log(data))
`
The fetch() function returns a Promise that resolves to a Response object. You can use the .json() method of the Response object to parse the response as JSON.

Note that both of these examples assume that the server you are making the request to will accept and process POST requests and will return a response in a format that you can handle (e.g. JSON). You will need to modify the examples to fit the specific requirements of your server and your application.

Top comments (0)