Categories
JavaScript Answers

How to make simple API Calls with Node.js?

Spread the love

To make simple API calls with Node.js, we use the http module.

For instance, we write

const http = require("http");
const client = http.createClient(3000, "localhost");
const request = client.request("PUT", "/users/1");
request.write("stuff");
request.end();
request.on("response", (response) => {
  // ...
});

to call createClient to create a client object.

Then we call request to start a put request to the /users/1 URL.

Then we call write to write the request body.

And we call end to send the request.

We call on to listen for the 'response' event which is triggered when we receive a response.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.