在 Netlify 函数中强制执行同源? (科尔斯)

Enforce same-origin in Netlify function? (cors)

我希望在我的 Netlify 站点中强制要求请求来自 process.env.URL 中的所需来源。但目前我既可以 cURL 又可以向 Postman 发出请求,并获得状态码为 200 的响应数据。我是否遗漏了什么?

exports.handler = async (event, context, callback) => {
  try {
    let id = event.rawUrl.split("/").pop();
    let response;
    switch (event.httpMethod) {
      case "GET":
        response = await prisma.like.count({ where: { postId: parseInt(id) } });
        break;

      case "POST":
        response = await prisma.like.create({
          data: { postId: parseInt(id) },
        });
        break;

      case "DELETE":
        response = await prisma.like.delete({
          where: {
            id: parseInt(id),
          },
        });
        break;
    }

    callback(null, {
      statusCode: 200,
      headers: {
        "Access-Control-Allow-Origin": process.env.URL,
        "Access-Control-Allow-Headers":
          "Origin, X-Requested-With, Content-Type, Accept",
        "Access-Control-Allow-Methods": "*",
        "Content-Type": "application/json",
      },
      body: JSON.stringify(response),
    });
    return;
  } catch (e) {
    console.error(e);
    return { statusCode: 500 };
  }
};

CORS 是浏览器的一项功能,即浏览器服从设置。 curl 不关心 CORS 并忽略它。