我在嘗試從 Google 獲取字體時偶然發現了 CORS 錯誤。
我目前有一個 express.js 服務器為 puppeteer 機器人提供 html 檔案。我需要使用自定義標頭欄位對向該服務器發送請求的用戶進行身份驗證。但是,當 html 檔案從 Google 獲取字體時,它會使用該自定義標頭,并且請求失敗并出現以下錯誤:
Access to font at 'http://fonts.gstatic.com/s/allura/v18/9oRPNYsQpS4zjuA_iwgW.woff2' from origin 'http://localhost:5000' has been blocked by CORS policy: Request header field test-token is not allowed by Access-Control-Allow-Headers in preflight response.
我在下面的一個小得多的腳本中復制了這個問題:
const puppeteer = require('puppeteer');
const express = require('express');
const app = express();
//middleware
app.use((req,res,next)=>{
//verify token
if(req.header("test-token") === "foobarbaz") return next();
})
app.use(express.static("public"));
app.listen(5000);
(async()=>{
const browser = await puppeteer.launch({
ignoreHTTPSErrors:true,
headless:true,
});
const page = await browser.newPage();
//for debug purposes
page.on("console",console.log);
page.setExtraHTTPHeaders({
"test-token":"foobarbaz"
})
await page.goto("http://localhost:5000/index.html");
const content = await page.content();
console.log(content);
})()
我加載了 Web 字體的示例 HTML 檔案:
<html>
<head>
<link rel="preconnect" href="//fonts.googleapis.com">
<link rel="preconnect" href="//fonts.gstatic.com" crossorigin>
<link href="//fonts.googleapis.com/css2?family=Allura&family=Bebas Neue&family=Bree Serif&family=Twinkle Star&display=swap" rel="stylesheet">
<style>
body{
font-family: 'Allura', cursive;
}
</style>
</head>
<body>
Hello world
</body>
</html>
我嘗試以某種方式洗掉 express.js 請求上的自定義標頭,但沒有運氣,如下所示:
app.use((req,res,next)=>{
//verify token
if(req.header("test-token") === "foobarbaz"){
res.removeHeader("text-token");
next();
}
})
如何在此自定義標頭上對用戶進行身份驗證,然后將其從 html 可能執行的進一步請求中洗掉(在這種情況下,加載外部網路字體)?
uj5u.com熱心網友回復:
而不是page.setExtraHTTPHeaders,請考慮使用page.setRequestInterception以便僅為對您的服務器的請求設定額外的標頭,而不是對 Google 服務器的請求。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/485265.html
標籤:javascript 表示 傀儡师
