![](/img/trans.png)
[英]How do I parse the body of a request using the http module in node.js?
[英]How do I use JSON in the body of an http PUT in node.js?
請參閱下面的代碼。 我正在嘗試在我的請求正文中發送{“status”:“accepted”}。 我一直從API返回的錯誤是:
{"message":"Unable to parse JSON in request body.","code":"invalid_json"}
我可以在Swift中使這個工作,但是我正在使用帶有設置的字典對象並將其序列化。 我不知道如何在Node.JS中這樣做。
var https = require('https')
var options = {
"host": "sandbox-api.uber.com",
"path": "/v1/sandbox/requests/" + req.body.request_id,
"method": "PUT",
"headers": {
"Authorization" : "Bearer " + req.body.bearer_token,
"Content-Type" : "application/json",
},
"body" : {
"status" : "accepted"
}
}
callback = function(response) {
var str = ''
response.on('data', function(chunk){
str += chunk
})
response.on('end', function(){
console.log(str)
})
}
https.request(options, callback).end()
您將其寫入請求對象,如:
var https = require('https')
var options = {
"host": "sandbox-api.uber.com",
"path": "/v1/sandbox/requests/" + req.body.request_id,
"method": "PUT",
"headers": {
"Authorization" : "Bearer " + req.body.bearer_token,
"Content-Type" : "application/json",
}
}
callback = function(response) {
var str = ''
response.on('data', function(chunk){
str += chunk
})
response.on('end', function(){
console.log(str)
})
}
var body = JSON.stringify({
status: 'accepted'
});
https.request(options, callback).end(body);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.