2011-12-30 33 views

回答

196

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. 
    } 
}); 
+11

'json'屬性是個把戲。 – 2016-01-08 03:41:15

+1

謝謝你這個有用的答案。最後我意識到這個選項是有據可查的。但是在豐富的人中間失去了...... – 2016-04-16 21:59:50

5

簡單的例子

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); 
}); 
0

正如official documentation說:

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)