我具有以下Typescript函数,假定已经使用Puppeteer启动了Chrome浏览器。可以在here中找到下面使用的Fetch函数的文档。
async function modify(client: CDPSession) {
client.on('Fetch.requestPaused', async ({ requestId, request, frameId, resourceType, responseErrorReason, responseStatusCode, responseHeaders, networkId }) => {
// Correctly prints out the User-Agent header's value
console.log(request.headers["User-Agent"]);
// After this line is run, I can inspect the request.headers object and see that User-Agent was successfully edited
request.headers['User-Agent'] = 'trying to edit this header';
// Continuing the request gives an error
await client.send('Fetch.continueRequest', {
requestId: requestId,
headers: request.headers,
});
});
}
这是我看到的具体错误:
错误:协议错误(Fetch.continueRequest):无效的参数标头:需要数组
如何解决此错误并成功修改request.headers
?这是我无法弄清楚的愚蠢的Javascript / Typescript语法问题吗?
答案 0 :(得分:1)
Fetch.requestPaused
将标头作为对象返回。例如:
{
"Upgrade-Insecure-Requests":"1",
"Accept": "text/html,application/xhtml+xml"}
}
Fetch.continueRequest
需要一个Array<{name: string, value: string}>
。例如
[
{"name": "Accept", value: "text/html,application/xhtml+xml"}
]
您可以使用Puppeteer使用的代码:
function headersArray(headers) {
const result = [];
for (const name in headers) {
if (!Object.is(headers[name], undefined))
result.push({name, value: headers[name] + ''});
}
return result;
}