在 Next.js 中实现 API 跨域(CORS) 调用

原文:How to Implement CORS for API Routes in Next.js

最近,发布了一个应用:Amazing Endemic Species,可以向其他开发人员提供了一组可用于二次开发的 API。

为了进行测试 API,我在自己的网站 shenlu.me 的 "Not Found" 页面中使用这些 API。然而,当我使用这些 API 时遇到了一些错误。

问题 #1: No 'Access-Control-Allow-Origin' Header

vbscript 复制代码
Access to fetch at 'http://aes.shenlu.me/api/v1/random' from origin 'http://localhost:1200' 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.

目前有两种方法可以解决这个问题:

  1. 在配置文件 next.config.js 中定义 CORS 头
  2. 创建一个中间件 (middleware.ts) 来处理请求

在配置文件 next.config.js 中定义 CORS 头

我使用了这种方法,并在 Amazing Endemic Speciesnext.config.mjs 文件中进行了如下配置:

csharp 复制代码
const nextConfig = {
  async headers() {
    return [
      {
        source: "/api/v1/:slug",
        headers: [
          {
            key: "Access-Control-Allow-Origin",
            value: "*", // 设置你的来源
          },
          {
            key: "Access-Control-Allow-Methods",
            value: "GET, POST, PUT, DELETE, OPTIONS",
          },
          {
            key: "Access-Control-Allow-Headers",
            value: "Content-Type, Authorization",
          },
        ],
      },
    ];
  },
  // 添加其他 Next.js 配置
}; 

定义中间件(middleware.ts)处理请求

第二种方法我没用,可以自己查看这个连接去配置:github.com/vercel/next...

问题 #2: next/image Un-configured Host

另一个错误是,当我直接将从 aes.shenlu.me/api/v1/rand... 获取的值 aes.shenlu.me/images/**.j... 传递给 src 时出现的。为了解决这个问题,我在 next.config.jsimages.remotePatterns 中定义了主机名 aes.shenlu.me

css 复制代码
const nextConfig = {
  // 可选地添加其他 Next.js 配置。
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "aes.shenlu.me",
        port: "",
        pathname: "/images/**",
      },
    ],
  },
};

解决这个问题后,我完成了如下的 "Not Found" 页面:

参考连接

相关推荐
人工智能训练师5 小时前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny075 小时前
pnpm相对于npm,yarn的优势
前端·npm·node.js
yddddddy6 小时前
css的基本知识
前端·css
昔人'6 小时前
css `lh`单位
前端·css
Nan_Shu_6148 小时前
Web前端面试题(2)
前端
知识分享小能手8 小时前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
数字化顾问9 小时前
GitHub热榜项目 - 日榜之应用场景与未来发展趋势
github
蚂蚁RichLab前端团队9 小时前
🚀🚀🚀 RichLab - 花呗前端团队招贤纳士 - 【转岗/内推/社招】
前端·javascript·人工智能
孩子 你要相信光9 小时前
css之一个元素可以同时应用多个动画效果
前端·css
huangql52010 小时前
npm 发布流程——从创建组件到发布到 npm 仓库
前端·npm·node.js