There's a quirk with the way setRequestInterception
and the 'request'
event work. Once activated, Puppeteer will send the POST data to every resource on the page, not just the original requested page. I was having the issue that all of my page resources (scripts, CSS) were failing to load once I added POST data in Puppeteer.
Since I only want to apply POST data to the first request, this code worked for me:
// Used for serializing POST parameters from an object
const querystring = require('querystring');
// ...
const browser = await puppeteer.launch();
const page = await browser.newPage();
let postData = {a: 1, b: 2};
await page.setRequestInterception(true);
page.once('request', request => {
var data = {
'method': 'POST',
'postData': querystring.stringify(postData),
'headers': {
...request.headers(),
'Content-Type': 'application/x-www-form-urlencoded'
},
};
request.continue(data);
// Immediately disable setRequestInterception, or all other requests will hang
page.setRequestInterception(false);
});
const response = await page.goto('https://www.example.com/');