如何在NodeJS中像這樣做一個HTTP請求?示例或模塊讚賞。發送Content-Type:application/json post與node.js
curl https://www.googleapis.com/urlshortener/v1/url \
-H 'Content-Type: application/json' \
-d '{"longUrl": "http://www.google.com/"}'
如何在NodeJS中像這樣做一個HTTP請求?示例或模塊讚賞。發送Content-Type:application/json post與node.js
curl https://www.googleapis.com/urlshortener/v1/url \
-H 'Content-Type: application/json' \
-d '{"longUrl": "http://www.google.com/"}'
Mikeal's request模塊可以做到這一點很容易:
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.
}
});
簡單的例子
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);
});
body - body body用於PATCH,POST和PUT請求。必須是一個Buffer,String或ReadStream。如果json爲true,則body必須是JSON序列化的對象。
發送JSON時,您只需將其放入選項主體即可。
var options = {
uri: 'https://myurl.com',
method: 'POST',
json: true,
body: {'my_date' : 'json'}
}
request(options, myCallback)
'json'屬性是個把戲。 – 2016-01-08 03:41:15
謝謝你這個有用的答案。最後我意識到這個選項是有據可查的。但是在豐富的人中間失去了...... – 2016-04-16 21:59:50