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

node.jsPostCurl

node.js Problem Overview


How can we make a HTTP request like this in NodeJS? Example or module appreciated.

curl https://www.googleapis.com/urlshortener/v1/url \
  -H 'Content-Type: application/json' \
  -d '{"longUrl": "http://www.google.com/"}'

node.js Solutions


Solution 1 - node.js

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.
  }
});

Solution 2 - node.js

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);  
}); 

Solution 3 - node.js

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)

Solution 4 - node.js

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/"})
});

Solution 5 - node.js

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/

Solution 6 - node.js

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()

Solution 7 - node.js

Using request with headers and post.

var options = {
            headers: {
                  'Authorization': 'AccessKey ' + token,
                  'Content-Type' : 'application/json'
            },
            uri: 'https://myurl.com/param' + value',
            method: 'POST',
            json: {'key':'value'}
 };
      
 request(options, function (err, httpResponse, body) {
    if (err){
         console.log("Hubo un error", JSON.stringify(err));
    }
    //res.status(200).send("Correcto" + JSON.stringify(body));
 })

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRadoslavView Question on Stackoverflow
Solution 1 - node.jsJosh SmithView Answer on Stackoverflow
Solution 2 - node.jsPoonam GuptaView Answer on Stackoverflow
Solution 3 - node.jsJiNView Answer on Stackoverflow
Solution 4 - node.jsPaul T. RawkeenView Answer on Stackoverflow
Solution 5 - node.jsShaiju TView Answer on Stackoverflow
Solution 6 - node.jsehrencronaView Answer on Stackoverflow
Solution 7 - node.jsCristian CardosoView Answer on Stackoverflow