7

I'm trying to make a POST request using puppeteer and send a JSON object in the request, however, I'm getting a timeout... if I'm trying to send a normal encoded form data that at least a get a reply from the server of invalid request... here is the relevant part of the code

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

I'm using the same code to make a GET request (without payload) and its working

Omid Nikrah
  • 2,444
  • 3
  • 15
  • 30
naoru
  • 2,149
  • 5
  • 34
  • 58

2 Answers2

5

postData needs to be encoded as form data (in the format key1=value1&key2=value2).

You can create the string on your own or use the build-in module querystring:

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

In case you need to submit JSON data:

            'postData': JSON.stringify(request)
Thomas Dondorf
  • 23,416
  • 6
  • 84
  • 105
2

If you are sending json, you need to add "content-type": "application/json". If you don't send it you can receive an empty response.

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