我正在使用 Express 和 Netlify 函数为 Chrome 扩展程序开发翻译 API。但是,我在从浏览器发出请求时遇到了 CORS 问题。预检 OPTIONS 请求失败,我一直在尝试解决问题。
这是我的服务器
import express from "express";
import cors from "cors";
import { getTranslation } from "./translator.js";
import serverless from "serverless-http";
const app = express();
const router = express.Router();
app.use(express.json());
app.use(
cors({
origin: "*",
methods: ["POST", "OPTIONS"],
allowedHeaders: ["Content-Type"],
})
);
router.options("/translate", cors(), (req, res) => {
res.sendStatus(204);
});
router.get("/", (req, res) => {
res.send("This is a translator app for DragWords chrome extension.");
});
router.post("/translate", async (req, res) => {
const body = req.body;
const { sourceText, targetLang } = body;
try {
const { translatedText } = await getTranslation({
text: sourceText,
targetLang: targetLang,
});
res.status(200).json({ translation: translatedText, serverError: null });
} catch (err) {
console.error(err);
res.status(500).json({ translation: null, serverError: err });
}
});
app.use("/.netlify/functions/api", router);
export const handler = serverless(app);
这是我的 netlify.toml
[build]
publish = "dist"
functions = "functions"
[context.production.environment]
DEEPL_API_KEY = "my api key"
[[headers]]
for = "/.netlify/functions/api/*"
[headers.values]
Access-Control-Allow-Origin = "*"
Access-Control-Allow-Methods = "POST, OPTIONS"
Access-Control-Allow-Headers = "Content-Type"
我在本地主机上运行此服务器:8888 我从“https://ricki-lee.medium.com”向服务器发送了一个请求 但仍然出现 CORS 错误。
https://ricki-lee.medium.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
这是我的 content.js 文件中的客户端代码,它从服务器获取翻译
async function getTranslation(sourceText) {
try {
const defaultTargetLang = await getDefaultTargetlang();
const response = await fetch("http://localhost:8888/translate", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
sourceText: sourceText,
targetLang: defaultTargetLang,
}),
});
const { translation, serverError } = await response.json();
if (serverError !== null) {
throw new Error(serverError);
}
return translation;
} catch (err) {
console.error(err);
return null;
}
}
我设置了 Access-Control-Allow-Origin = "*" 但似乎不起作用
我还使用curl测试了OPTIONS请求,返回了以下错误:
curl -X OPTIONS http://localhost:8888/translate -H "Origin: https://ricki-lee.medium.com"
Method Not Allowed
如何配置我的 Express 服务器或 Netlify 设置以正确处理预检
OPTIONS
请求并解决 CORS 错误?
您的 CORS 请求的来源位于公共云中,而它调用的 URL 位于您的专用网络中。在这种情况下,预检请求包含
Access-Control-Request-Private-Network: true
并且响应必须包含
Access-Control-Allow-Private-Network: true
(另请参阅 https://developer.chrome.com/blog/private-network-access-preflight)。
cors
包没有设置这个响应头。您可以使用以下代码自行设置:
app.use(cors({..., preflightContinue: true}))
.options("*", function(req, res) {
if (res.get("Access-Control-Allow-Origin"))
res.set("Access-Control-Allow-Private-Network", "true");
res.end();
});