How to intercept HTTP OPTIONS calls made by the browser

我们两清 提交于 2020-01-21 10:17:04

问题


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:


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


来源:https://stackoverflow.com/questions/59761736/how-to-intercept-http-options-calls-made-by-the-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!