使用具有 JSON 负载的 puppeteer 发出 POST 请求

Making a POST request using puppeteer with JSON payload

我正在尝试使用 puppeteer 发出 POST 请求并在请求中发送 JSON 对象,但是,我遇到了超时...如果我正在尝试发送一个正常的编码表单数据,至少可以从服务器获得无效请求的回复... 这是代码的相关部分

await page.setRequestInterception(true);
    const request = {"mac": macAddress, "cmd": "block"};
    page.on('request', interceptedRequest => {

        var data = {
            'method': 'POST',
            'postData': request
        };

        interceptedRequest.continue(data);
    });
    const response = await page.goto(configuration.commandUrl);     
    let responseBody = await response.text();

我正在使用相同的代码来发出 GET 请求(没有负载)及其工作方式

postData需要编码为表单数据(格式key1=value1&key2=value2)。

您可以自己创建字符串或使用内置模块querystring:

const querystring = require('querystring');
// ...
        var data = {
            'method': 'POST',
            'postData': querystring.stringify(request)
        };

如需提交JSON数据:

            'postData': JSON.stringify(request)

如果您要发送json,您需要添加"content-type":"application/json"。如果您不发送它,您可能会收到一个空响应。

var data = {
    method : 'POST',
    postData: '{"test":"test_data"}',
    headers: { ...interceptedRequest.headers(), "content-type": "application/json"}
};
interceptedRequest.continue(data);