ItSolutionStuff.com

Node JS Http Request with Headers Example

By Hardik Savani • May 5, 2021
Node JS

Hello,

In this tutorial, you will learn node js http request with headers. i would like to share with you node js post request with headers. you will learn node js http get with headers. this example will help you node js make get request with headers.

i will give you two examples, using axios and request npm package for male post http request with pass headers using node js. let's see both example with output as bellow:

Example 1: HTTP Request with Headers using Axios

Create Node App:

mkdir my-request-app

cd my-request-app

npm init

Install Axios:

npm install axios --save

server.js

const axios = require('axios');

const data = {

first_name: 'Hardik',

last_name: 'Savani',

email: 'hardik@gmail.com'

};

const options = {

headers: {'Accept': 'application/json'}

};

axios.post('https://api.mywebtuts.com/api/users', data, options)

.then((res) => {

console.log(`Status: ${res.status}`);

console.log('Body: ', res.data);

}).catch((err) => {

console.error(err);

});

Run App

node server.js

Output

Status: 200

Body: {

first_name: 'Hardik',

last_name: 'Savani',

email: 'hardik@gmail.com',

created_at: '2021-05-04T12:49:03.879271Z'

}

Example 2: HTTP Request Headers using Request

Create Node App:

mkdir my-request-app

cd my-request-app

npm init

Install Axios:

npm install request --save

server.js

const request = require('request');

const options = {

url: 'https://api.mywebtuts.com/api/users',

json: true,

body: {

first_name: 'Hardik',

last_name: 'Savani',

email: 'hardik@gmail.com'

},

headers: {'Accept': 'application/json'}

};

request.post(options, (err, res, body) => {

if (err) {

return console.log(err);

}

console.log(`Status: ${res.statusCode}`);

console.log(body);

});

Run App

node server.js

Output

Status: 200

{

first_name: 'Hardik',

last_name: 'Savani',

email: 'hardik@gmail.com',

created_at: '2021-05-04T12:49:24.585309Z'

}

I hope it can help you...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Node JS Make HTTP Delete Request Example

Read Now →

Node JS Make Http Get Request with Parameters Example

Read Now →

How to make an HTTP POST request in Node JS?

Read Now →

How to run node js server on https using self-signed certificate?

Read Now →

Node JS Express Form Submission Example

Read Now →

Node JS Mysql Connection Example

Read Now →

Node JS Multer Rename Uploaded File Example

Read Now →

Node JS Convert Image File to Base64 String Example

Read Now →

Node JS Resize Image Before Upload using Multer Sharp

Read Now →

Multiple File Upload in Node JS using Multer Example

Read Now →