node js使用原始请求主体发送post请求

Zac*_*c S 9 post node.js

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)
            }
        }
    );
Run Code Online (Sandbox Code Playgroud)

我想在req变量中发送原始请求体.它正在邮递员,但在节点js我无法发送原始json作为发布请求的请求主体.

Tho*_*ans 11

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

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

json: true如果您要发送JSON ,则可以添加该选项,而不是设置标题.


Kel*_*ila 2

将 更改为Content-Typeapplication/json因为您的正文采用 JSON 格式。