在CORS中,浏览器会首先发送一个OPTIONS请求,用于确定是否允许跨域请求。服务器返回的响应头需要包含Access-Control-Allow-Origin,允许的源列表。如果该值为"*",则允许来自所有源的请求。
以下是使用Node.js和Express框架实现CORS的示例代码:
const express = require("express");
const app = express();
// 添加CORS中间件
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
res.setHeader("Access-Control-Allow-Credentials", true);
if (req.method === "OPTIONS") {
return res.sendStatus(204);
}
next();
});
// 处理API请求
app.get("/api/data", (req, res) => {
res.json({ message: "API data response" });
});
// 启动服务器
app.listen(3000, () => {
console.log("Server start at http://localhost:3000");
});
在上述代码中,使用了一个中间件添加了必要的CORS响应头,设置了允许的源、方法、请求头和是否允许携带认证信息。并在OPTIONS请求中返回204状态码。在使用API时,只需要使用正确的URL即可。例如在前端使用fetch请求:
fetch("http://localhost:3000/api/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
此时就可以从API请求到数据并处理。