0
0
NodejsHow-ToBeginner · 3 min read

How to Send JSON Data in Request in Node.js Easily

To send JSON data in a request in Node.js, set the Content-Type header to application/json and send the JSON string in the request body. You can use the built-in http or https modules or libraries like node-fetch or axios to do this easily.
📐

Syntax

When sending JSON data in a request, you need to:

  • Set the Content-Type header to application/json so the server knows you are sending JSON.
  • Convert your JavaScript object to a JSON string using JSON.stringify().
  • Include the JSON string in the request body.
javascript
const data = JSON.stringify({ key: 'value' });

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

Example

This example shows how to send JSON data in a POST request using the built-in https module in Node.js.

javascript
import https from 'https';

const data = JSON.stringify({ name: 'Alice', age: 25 });

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

const req = https.request(options, (res) => {
  let responseBody = '';
  res.on('data', (chunk) => {
    responseBody += chunk;
  });
  res.on('end', () => {
    console.log('Response:', responseBody);
  });
});

req.on('error', (error) => {
  console.error('Error:', error);
});

req.write(data);
req.end();
Output
{"id":101,"name":"Alice","age":25}
⚠️

Common Pitfalls

Common mistakes when sending JSON data in Node.js requests include:

  • Not setting the Content-Type header to application/json, causing the server to misinterpret the data.
  • Forgetting to convert the JavaScript object to a JSON string with JSON.stringify().
  • Not setting the Content-Length header correctly, which can cause the request to hang or fail.
javascript
/* Wrong way: sending object directly without stringifying and missing headers */

const data = { name: 'Bob' };

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

const req = https.request(options, (res) => {
  // handle response
});

req.write(data); // This will cause an error
req.end();

/* Right way: stringify and set headers */

const jsonData = JSON.stringify(data);

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

const correctReq = https.request(correctOptions, (res) => {
  // handle response
});

correctReq.write(jsonData);
correctReq.end();
📊

Quick Reference

Remember these key points when sending JSON data in Node.js requests:

  • Always stringify your data with JSON.stringify().
  • Set the Content-Type header to application/json.
  • Set the Content-Length header to the byte length of the JSON string.
  • Use https or libraries like axios or node-fetch for easier HTTP requests.

Key Takeaways

Always convert your JavaScript object to a JSON string using JSON.stringify() before sending.
Set the Content-Type header to application/json to inform the server about the data format.
Include the Content-Length header with the correct byte length of the JSON string.
Use Node.js built-in https module or popular libraries like axios for simpler HTTP requests.
Avoid sending raw objects or missing headers to prevent request errors or server misinterpretation.