Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a POST request using puppeteer with JSON payload

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

like image 425
naoru Avatar asked Oct 29 '18 15:10

naoru


People also ask

What is JSON request payload?

A request payload is data that clients send to the server in the body of an HTTP POST, PUT, or PATCH message that contains important information about the request.


2 Answers

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)
like image 102
Thomas Dondorf Avatar answered Sep 20 '22 21:09

Thomas Dondorf


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);
like image 45
Edgar Uribe Avatar answered Sep 22 '22 21:09

Edgar Uribe