Answers:
Mikeal的请求模块可以轻松做到这一点:
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.
}
});
headers: {'content-type' : 'application/json'},
选项,它才对我有用。
简单的例子
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);
});
使用带有标题和帖子的请求。
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));
})
由于request
不建议使用其他答案的模块,我建议切换到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()