【问题标题】:How do I use JSON in the body of an http PUT in node.js?如何在 node.js 中的 http PUT 正文中使用 JSON?
【发布时间】:2015-11-26 02:20:25
【问题描述】:

请参阅下面的代码。我正在尝试在我的请求正文中发送 { "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()

【问题讨论】:

  • 内置的 http 库是相当准系统的。使用像request 这样更高级别的东西要容易得多,它会为您处理很多细节。

标签: javascript node.js http-request uber-api


【解决方案1】:

您将其写入请求对象,例如:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    相关资源
    最近更新 更多