在 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" 页面:

参考连接

相关推荐
天下无贼!1 小时前
2024年最新版Vue3学习笔记
前端·vue.js·笔记·学习·vue
Jiaberrr1 小时前
JS实现树形结构数据中特定节点及其子节点显示属性设置的技巧(可用于树形节点过滤筛选)
前端·javascript·tree·树形·过滤筛选
赵啸林1 小时前
npm发布插件超级简单版
前端·npm·node.js
罔闻_spider2 小时前
爬虫----webpack
前端·爬虫·webpack
吱吱鼠叔2 小时前
MATLAB数据文件读写:1.格式化读写文件
前端·数据库·matlab
爱喝水的小鼠2 小时前
Vue3(一) Vite创建Vue3工程,选项式API与组合式API;setup的使用;Vue中的响应式ref,reactive
前端·javascript·vue.js
盏灯2 小时前
前端开发,场景题:讲一下如何实现 ✍电子签名、🎨你画我猜?
前端
WeiShuai2 小时前
vue-cli3使用DllPlugin优化webpack打包性能
前端·javascript
Wandra2 小时前
很全但是超级易懂的border-radius讲解,让你快速回忆和上手
前端
ice___Cpu2 小时前
Linux 基本使用和 web 程序部署 ( 8000 字 Linux 入门 )
linux·运维·前端