我有一个用例,我想拦截并记录 HTTP OPTIONS 调用。我了解这些是由浏览器作为 CORS 的一部分完成的
我尝试过猴子修补 XMLHttpRequest,也尝试过服务 worker ,我可以通过“fetch”事件进行拦截。
但是我只能捕获非 OPTIONS 调用(GET、PUT、POST)
如何拦截 OPTIONS 调用?我清楚地看到它们是在网络选项卡中完成的
最佳答案
CORS 预检请求作为浏览器安全实现硬编码到浏览器中,并且不会通过可编程 API 向我们公开。从本质上讲,拦截或更改预检请求可能会破坏 CORS 本身的安全性。
由于 Chrome 开发工具网络选项卡中提供 OPTIONS
请求,因此您可以使用 Puppeteer ,它使用 Chrome 开发工具协议(protocol)来访问较低级别的网络请求。 page.setRequestInterception()
将捕获OPTIONS
请求。
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())
}
关于javascript - 如何拦截浏览器发出的 HTTP OPTIONS 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59761736/