使用Node.js发送带有原始请求体的POST请求

11
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变量中。在Postman上可以工作,但在Node.js中,我无法将原始JSON作为POST请求的请求主体发送。


什么是错误?你的 "content-type": "application/x-www-form-urlencoded" 可能不正确,因为你正在发送 JSON。它应该是 application/json - Kelly Keller-Heikkila
POST /HTTP/JSON/Prices/GetPriceSheet.aspx HTTP/1.1 Host: host.com Content-Type: application/x-www-form-urlencoded Cache-Control: no-cache{ "request": { "header": { "username": "name", "password": "pw" }, "body": { "shape":"round" } } } 这是在Postman上工作的请求预览。因此,我需要在标头中使用x-www-form-urlencoded,但也发送原始的json数据。我收到的错误是来自REST服务的格式错误。 - Zack Sac S
3个回答

15

您正在尝试发送 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而不必设置头。


2

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


尝试过了,但是头部还需要 "content-type": "application/x-www-form-urlencoded"。 - Zack Sac S
然后你必须将你的请求体格式更改为该格式,而不是JSON。 - Kelly Keller-Heikkila
是的,我猜那就是问题所在。我不需要JSON,而是需要根据内容类型在查询字符串中获取数据。我会尝试弄清楚x-www-form的格式。谢谢。 - Zack Sac S

1
在正文中添加字符串时,在头部添加“Content-Length”将解决此问题。对我很有用。
头部:{"Cache-Control": "no-cache", "Content-Type":"application/json;charset=UTF-8",'Content-Length': req.length}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接