Node Js Set HTTP Headers in HTTP Post Request Tutorial

Node js set HTTP Headers example; We are pretty sure you are familiar with HTTP requests; what if we told you to make an HTTP request. Your answer will probably be yes, but how about adding the additional information with an HTTP request.

In this quick Node js tutorial, we will teach you how to make a simple HTTP post request, add additional information in HTTP requests using HTTP headers.

HTTP Headers provide a simple mechanism to send additional information with an HTTP request and Axios makes server communication easy with its wide array of HTTP methods.

We will use the Axios client to trigger the HTTP request in Node. Specifically, we will use the post() method.

We will create a single object bind with the httpOptions variable, set headers property, and send ‘Accept’: ‘application/json’ as headers metadata in node app.

Using Axios for managing server requests has its own benefits. First of all, it works on an Asynchronous pattern, which means it returns a then-able response.

Handling response and errors are super easy with Axios. On the other hand, it provides tons of features.

Communicating with the server can also be made easy with its powerful request config option; you can make a request with config options.

You have to create a request options object and pass in the request Axios request method as an argument to initiate the config. You will learn how to create a header object and send it to the server.

Furthermore, you can also create custom headers in the node js app.

How to Add HTTP Headers in Node Js HTTP Request

  • Step 1: Create App Folder
  • Step 2: Build Package JSON
  • Step 3: Create Server File
  • Step 4: Add Axios Module
  • Step 5: Set Up Headers in HTTP Request
  • Step 6: Test HTTP Output

Create App Folder

Let us make a new directory, in this folder we will keep the code o our node app.

mkdir node-demo

Head over to the directory with below command.

cd node-demo

Build Package JSON

The package file is something that we require to create right now. But why this file?

In order to work with headers and HTTP requests, we will need an external dependency.

An external package has to be registered in the package.json file, and you can create that file by executing the below command.

npm init

Create Server File

Now, into your project folder, make a new file and name it server.js.

In next step, we will configure the node command. So open the package.json file, inside the scripts array, look for node property and append the server.js file name.

  "scripts": {
    "start": "node server.js"
  },

Add Axios Module

Here is the command that will help you add the Axios module into the node project.

npm install axios

Set Up Headers in HTTP Request

First, open the server.js file, copy the complete given code and paste into your file.

const axios = require('axios')

const userObject = {
  name: 'Kylian Mbappe',
  email: 'mbappe@fifa.com',
  profession: 'Footballer',
  goals: 555,
}

const headerOptions = {
  headers: { Accept: 'application/json' },
}

axios
  .post('http://localhost:3000/users', userObject, headerOptions)
  .then((res) => {
    if (res.status === 201) {
      console.log('Request body :', res.data)
      console.log('Request header :', res.headers)
    }
  })
  .catch((e) => {
    console.error('Error occurred : ' + e)
  })

HTTP Headers might be set in various contexts; however, the primary purpose remains the same that is to pass additional information with the HTTP request.

The following code example is simply just adding the simple header, but there are many types of Headers that can be set based on the request types and need.

If you want to know deeply about HTTP headers, please do checkout the MDN HTTP headers doc.

Test HTTP Output

Now, we will show you how to send the HTTP request that leads us to our final task.

In our final task we will start the node server using the following command.

node server.js

After the request is sent, you will see given response.

Request body : {
  name: 'Kylian Mbappe',
  email: 'mbappe@fifa.com',
  profession: 'Footballer',
  goals: 555,
  id: 4
}

Request header : {
  'x-powered-by': 'Express',
  vary: 'Origin, X-HTTP-Method-Override, Accept-Encoding',
  'access-control-allow-credentials': 'true',
  'cache-control': 'no-cache',
  pragma: 'no-cache',
  expires: '-1',
  'access-control-expose-headers': 'Location',
  location: 'http://localhost:3000/users/4',
  'x-content-type-options': 'nosniff',
  'content-type': 'application/json; charset=utf-8',
  'content-length': '116',
  etag: 'W/"74-Xo29cVR1bVv37gRSOzrCXv/AcNM"',
  date: 'Thu, 23 Dec 2021 20:26:34 GMT',
  connection: 'close'
}

Conclusion

Node Js Set HTTP Headers in HTTP Post Request Tutorial

In this Node Axios HTTP headers tutorial, we have learned how to add headers in HTTP requests within the node js environment.

We have gone through every step to determine how does the request configurations added in an HTTP request in the node js app.