How to intercept HTTP OPTIONS calls made by the br

2020-05-08 11:45发布

I have a use case where I'd like to intercept and log HTTP OPTIONS calls. I understand these are being done by the browser as part of CORS

I've tried monkeypatching XMLHttpRequest, and also a service-worker where I'd intercept via the "fetch" event.

However I am only ever able to capture non OPTIONS calls (GET, PUT, POST)

How can I intercept the OPTIONS calls? I clearly see them being done in the network tab

1条回答
兄弟一词,经得起流年.
2楼-- · 2020-05-08 12:21

CORS preflight requests are hard-coded into browsers as a browser security implementation and are not exposed to us via programmable APIs. By nature, intercepting or altering preflight requests could negate the security of CORS itself.

Because OPTIONS requests are available in Chrome Dev Tools network tab, you can use Puppeteer, which uses the Chrome Dev Tools protocol to access lower-level network requests. page.setRequestInterception() will capture OPTIONS requests.

main.mjs

import puppeteer from 'puppeteer';

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  page.on('request', debugRequest);

  await page.setRequestInterception(true);

  await page.evaluate(() => {
    // custom request headers should force preflight CORS requests
    // (see https://www.w3.org/TR/cors/#resource-preflight-requests)
    fetch('https://example.com', {
      headers: {
        'force-preflight-request': null
      }
    });
  })

  await browser.close();
})()

function debugRequest(request) {
  console.log(request.method(), request.url())
}
查看更多
登录 后发表回答