2011-12-30 24 views

Trả lời

196

Mikeal's request mô-đun có thể làm điều này một cách dễ dàng:

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

Thuộc tính 'json' là thủ thuật. –

+1

Cảm ơn bạn vì câu trả lời hữu ích này. Cuối cùng, tôi nhận ra rằng tùy chọn được ghi nhận tốt. Nhưng bị mất ở giữa nhiều người khác ... –

5

Ví dụ đơn giản

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

Khi official documentation nói:

body - body body cho các yêu cầu PATCH, POST và PUT. Phải là Bộ đệm, Chuỗi hoặc ReadStream. Nếu json là true, thì body phải là một đối tượng có thể tuần tự hóa JSON.

Khi gửi JSON, bạn chỉ cần đặt nó vào phần nội dung của tùy chọn.

var options = { 
    uri: 'https://myurl.com', 
    method: 'POST', 
    json: true, 
    body: {'my_date' : 'json'} 
} 
request(options, myCallback) 
Các vấn đề liên quan