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()
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)
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));
})
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({_x000D_
uri: 'https://www.googleapis.com/urlshortener/v1/url',_x000D_
headers: {'Content-Type': 'application/json'},_x000D_
body: JSON.stringify({"longUrl": "http://www.google.com/"})_x000D_
});
_x000D_
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);
});
Source: Stackoverflow.com