在 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 Species 的 next.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.js 的 images.remotePatterns 中定义了主机名 aes.shenlu.me。

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

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

参考连接

相关推荐
IT_陈寒7 分钟前
SpringBoot自动配置的坑我帮你踩过了
前端·人工智能·后端
miofly11 分钟前
GitHub 日榜趋势速报 | 2026-10-05
开源·github
m4Rk_15 分钟前
【论文阅读】Agent 记忆机制(90):HyperMem——用超图建模长期记忆中的高阶关联
论文阅读·人工智能·学习·开源·github
其实防守也摸鱼29 分钟前
网安自测题:掌握核心知识点的实用练习
linux·运维·服务器·前端·数据库·sql·xss
星恒随风37 分钟前
Linux开发工具详解(二):Git版本控制、GitHub协作与GDB调试实战
linux·笔记·git·学习·github
cuijiecheng20181 小时前
Windows 下使用 GitHub Private Repository 管理私人 Visual Studio/C++ 项目
windows·github·visual studio
geovindu3 小时前
css: Timeline scribble
前端·css·iphone
怕浪猫7 小时前
GEO 优化到底是什么?AI时代内容创作者必须懂的新技能
算法·面试·github
miofly9 小时前
Aleph Alpha 开源 78B 参数 MoE 模型 Kolibri
开源·github
JackSparrow41410 小时前
和AI一起将全部CSDN博文迁移到个人博客站
人工智能·程序人生·ai·github·cloudflare·astro·静态博客