0
0
NodejsHow-ToBeginner · 4 min read

How to Make POST Request in Node.js: Simple Guide

To make a POST request in Node.js, you can use the native https module or popular libraries like axios. The https module requires setting request options and writing data to the request body, while axios simplifies this with a single function call.
📐

Syntax

Using the native https module, you create a request with options specifying method, headers, and URL. Then you write the data to the request body and end the request.

With axios, you call axios.post(url, data, config) where url is the endpoint, data is the payload, and config holds headers or other settings.

javascript
const https = require('https');

const data = JSON.stringify({ key: 'value' });

const options = {
  hostname: 'example.com',
  path: '/api',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(data)
  }
};

const req = https.request(options, res => {
  console.log(`Status: ${res.statusCode}`);
  res.on('data', d => process.stdout.write(d));
});

req.on('error', error => console.error(error));

req.write(data);
req.end();
💻

Example

This example shows how to make a POST request to a JSON placeholder API using axios. It sends JSON data and logs the response.

javascript
import axios from 'axios';

async function makePostRequest() {
  try {
    const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
      title: 'foo',
      body: 'bar',
      userId: 1
    });
    console.log('Response data:', response.data);
  } catch (error) {
    console.error('Error making POST request:', error);
  }
}

makePostRequest();
Output
{ id: 101, title: 'foo', body: 'bar', userId: 1 }
⚠️

Common Pitfalls

  • Forgetting to set Content-Type header to application/json when sending JSON data.
  • Not calling req.end() when using the native https module, which causes the request to hang.
  • Not handling errors with req.on('error') or try/catch in async functions.
  • Sending data as a plain object instead of stringifying it with JSON.stringify() when using native modules.
javascript
/* Wrong way: Missing Content-Type and not ending request */
const https = require('https');
const data = { key: 'value' };

const options = {
  hostname: 'example.com',
  path: '/api',
  method: 'POST'
};

const req = https.request(options, res => {
  console.log(`Status: ${res.statusCode}`);
});

req.write(JSON.stringify(data)); // Corrected: data should be string or buffer
// req.end() missing - request never sent

/* Right way: */
const dataCorrect = JSON.stringify({ key: 'value' });

const optionsCorrect = {
  hostname: 'example.com',
  path: '/api',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(dataCorrect)
  }
};

const reqCorrect = https.request(optionsCorrect, res => {
  console.log(`Status: ${res.statusCode}`);
});

reqCorrect.on('error', error => console.error(error));
reqCorrect.write(dataCorrect);
reqCorrect.end();
📊

Quick Reference

Use https.request() for native POST requests with manual setup. Use axios.post() for simpler syntax and automatic JSON handling. Always set Content-Type header and handle errors.

MethodDescriptionExample
https.requestNative Node.js method for HTTP requestshttps.request(options, callback)
axios.postSimplified HTTP POST with promisesaxios.post(url, data, config)
JSON.stringifyConvert object to JSON stringJSON.stringify({ key: 'value' })
req.end()Ends native request and sends itreq.end()

Key Takeaways

Use the native https module or axios library to make POST requests in Node.js.
Always set the Content-Type header to application/json when sending JSON data.
Call req.end() to complete native https requests, or use axios for simpler syntax.
Handle errors properly to avoid silent failures.
Stringify data with JSON.stringify() before sending in native requests.