Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send Content-Type: application/json post with node.js

Tags:

post

node.js

curl

People also ask

Can we send JSON object in post request?

To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.

How do I use Content-Type in node JS?

use(function(req, res, next) { req. header("Content-Type", "application/json"); res. header("Content-Type", "application/json"); next(); });


Mikeal's request module can do this easily:

var request = require('request');

var options = {
  uri: 'https://www.googleapis.com/urlshortener/v1/url',
  method: 'POST',
  json: {
    "longUrl": "http://www.google.com/"
  }
};

request(options, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body.id) // Print the shortened url.
  }
});

Simple Example

var request = require('request');

//Custom Header pass
var headersOpt = {  
    "content-type": "application/json",
};
request(
        {
        method:'post',
        url:'https://www.googleapis.com/urlshortener/v1/url', 
        form: {name:'hello',age:25}, 
        headers: headersOpt,
        json: true,
    }, function (error, response, body) {  
        //Print the Response
        console.log(body);  
}); 

As the official documentation says:

body - entity body for PATCH, POST and PUT requests. Must be a Buffer, String or ReadStream. If json is true, then body must be a JSON-serializable object.

When sending JSON you just have to put it in body of the option.

var options = {
    uri: 'https://myurl.com',
    method: 'POST',
    json: true,
    body: {'my_date' : 'json'}
}
request(options, myCallback)

For some reason only this worked for me today. All other variants ended up in bad json error from API.

Besides, yet another variant for creating required POST request with JSON payload.

request.post({
    uri: 'https://www.googleapis.com/urlshortener/v1/url',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({"longUrl": "http://www.google.com/"})
});

Axios is Lesser and Better:

const data = JSON.stringify({
  message: 'Hello World!'
})

const url = "https://localhost/WeatherAPI";

axios({
    method: 'POST',
    url, 
    data: JSON.stringify(data), 
    headers:{'Content-Type': 'application/json; charset=utf-8'}
}) 
  .then((res) => {
    console.log(`statusCode: ${res.status}`)
    console.log(res)
  })
  .catch((error) => {
    console.error(error)
  })

Also check 5 Ways to Make HTTP Requests in Node.js

https://www.twilio.com/blog/2017/08/http-requests-in-node-js.html

Refer:

https://nodejs.dev/learn/make-an-http-post-request-using-nodejs

https://flaviocopes.com/node-http-post/

https://stackabuse.com/making-asynchronous-http-requests-in-javascript-with-axios/


Since the request module that other answers use has been deprecated, may I suggest switching to node-fetch:

const fetch = require("node-fetch")

const url = "https://www.googleapis.com/urlshortener/v1/url"
const payload = { longUrl: "http://www.google.com/" }

const res = await fetch(url, {
  method: "post",
  body: JSON.stringify(payload),
  headers: { "Content-Type": "application/json" },
})

const { id } = await res.json()