【问题标题】:node js send post request with raw request body节点 js 发送带有原始请求正文的 post 请求
【发布时间】:2016-02-11 18:00:43
【问题描述】:
var req ={
      "request": {
        "header": {
          "username": "name",
          "password": "password"
        },
        "body": {
        "shape":"round"    
    }
      }
    };

    request.post(
        {url:'posturl',

        body: JSON.stringify(req),
        headers: { "content-type": "application/x-www-form-urlencoded"}
        },
        function (error, response, body) {        
            if (!error && response.statusCode == 200) {
                console.log(body)
            }
        }
    );

我想在 req 变量中发送原始请求正文。它正在使用邮递员,但在节点 js 中,我无法将原始 json 作为发布请求的请求正文发送。

【问题讨论】:

  • 错误是什么?你的"content-type": "application/x-www-form-urlencoded" 可能不正确,因为你正在发送 JSON?应该是application/json
  • POST /HTTP/JSON/Prices/GetPriceSheet.aspx HTTP/1.1 主机:host.com 内容类型:application/x-www-form-urlencoded 缓存控制:no-cache { "request ": { "header": { "username": "name", "password": "pw" }, "body": { "shape":"round" } } } 这是 postman 上的请求预览。所以我需要在标头中使用 x-www-form-urlencoded,但也需要发送原始 json 数据。我得到的错误是来自休息服务的错误格式。

标签: node.js post


【解决方案1】:

Content-Type 更改为 application/json,因为您的正文是 JSON 格式。

【讨论】:

  • 试过了,但是 "content-type": "application/x-www-form-urlencoded" 也是标题的要求。
  • 那么你必须将你的 body 改为该格式,而不是 JSON。
  • 是的,我想这就是我不需要 json 而是根据内容类型查询字符串中的数据的问题。我会尝试找出 x-www-form 的格式。谢谢。
【解决方案2】:

您正在尝试发送 JSON(您的 req 变量),但您将其解析为字符串(JSON.stringify(req))。由于您的路线需要 JSON,它可能会失败并返回错误。请尝试以下请求:

request.post({
    url: 'posturl',
    body: req,
    json: true
}, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body)
    }
});

如果您发送 JSON,您可以添加选项 json: true,而不是设置您的标头。

【讨论】:

    【解决方案3】:

    在正文中添加的字符串的标头中添加“Content-Length”,将解决此问题。 它对我有用。

    headers:{"Cache-Control": "no-cache", "Content-Type":"application/json;charset=UTF-8",'Content-Length': req.length强>}

    【讨论】:

      猜你喜欢
      • 2021-03-12
      • 2015-12-02
      • 1970-01-01
      • 2017-08-19
      • 1970-01-01
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多