发送Content-Type:application / json post与node.js
我们如何在NodeJS中这样做一个HTTP请求? 示例或模块表示赞赏。
curl https://www.googleapis.com/urlshortener/v1/url \ -H 'Content-Type: application/json' \ -d '{"longUrl": "http://www.google.com/"}'
迈克尔的请求模块可以很容易地做到这一点:
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); });