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

7

124

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/"}'
Spit answered 30/12, 2011 at 2:53 Comment(0)
P
2

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/

Proprietor answered 11/5, 2021 at 18:55 Comment(0)
S
296

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.
  }
});
Supertax answered 30/12, 2011 at 2:55 Comment(4)
Thank you for this helpful answer. In the end I realize the option is well documented. But lost in the middle of plenty others...Physical
It didn't worked for me until i added the headers: {'content-type' : 'application/json'}, option.Sidecar
- the NodeJs 'request' module is deprecated. - how would we do this using 'http' module ? Thank you.Barozzi
Axios is Lesser and Better: , Check this post.Proprietor
B
12

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);  
}); 
Brain answered 15/6, 2017 at 6:52 Comment(0)
T
12

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)
Thespian answered 9/3, 2018 at 7:54 Comment(1)
Is it just me or its documentation sucks?Intercommunicate
A
4

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/"})
});
Andria answered 4/7, 2018 at 10:26 Comment(0)
P
2

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()
Phiphenomenon answered 20/7, 2020 at 14:40 Comment(0)
P
2

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/

Proprietor answered 11/5, 2021 at 18:55 Comment(0)
R
0

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));
 })
Raving answered 19/7, 2020 at 2:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.