问题
I'm tinkering with the headless chrome node api called puppeteer
.
I'm wondering how to listen to a specific request response and how to act in consequence.
I have look at events requestfinish
and response
but it gives me all the request/responses already performed in the page.
How can I achieve commented behaviour?
Thanks !
回答1:
One option is to do the following:
page.on('response', response => {
if (response.url().endsWith("your/match"))
console.log("response code: ", response.status());
// do something here
});
This still catches all requests, but allows you to filter and act on the event emitter.
https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#event-response
回答2:
Filtered response (wait up to 11 seconds) body parsed as JSON with initially requested PATCH or POST method every time you will be call that:
const finalResponse = await page.waitForResponse(response =>
response.url() === urlOfRequest
&& (response.request().method() === 'PATCH'
|| response.request().method() === 'POST'), 11);
let responseJson = await finalResponse.json();
console.log(responseJson);
回答3:
I was using jest-puppeteer and trying to test for a specific response code of my test server. page.goto()
resolves to the response of the original request.
Here is a simple test that a 404
response is returned when expected.
describe(`missing article page`, () => {
let response;
beforeAll(async () => {
response = await page.goto('http://my-test-server/article/this-article-does-not-exist')
})
it('has an 404 response for missing articles', () => {
expect(response.status()).toEqual(404)
})
it('has a footer', async () => {
await expect(page).toMatch('My expected footer content')
})
})
回答4:
Since puppeteer v1.6.0
(I guess) you can use page.waitForResponse(urlOrPredicate[, options])
Example usage from docs:
const firstResponse = await page.waitForResponse('https://example.com/resource');
const finalResponse = await page.waitForResponse(response => response.url() === 'https://example.com' && response.status() === 200);
return finalResponse.ok();
来源:https://stackoverflow.com/questions/45822058/puppeteer-how-to-listen-to-a-specific-response