ค้นหาเว็บไซต์

javascript - การเขียนทับ middleware ของ NextJS 13 ไม่ทำงานอย่างถูกต้องสำหรับวิธีการ POST


ฉันเขียน middleware ของ NextJS ที่เขียนทับคำขอไปยังเซิร์ฟเวอร์ภายในอื่น

import {NextRequest, NextResponse, URLPattern} from "next/server";
import {endpoint} from "@/utils";

export const config = {
    matcher: "/api/:path*"
}

const pattern = new URLPattern({pathname: "/api/:path*"})

export async function middleware(req: NextRequest) {

    const result = pattern.exec(req.url)

    console.log(result)
    if (result) {
        const path = result.pathname.groups.path

        return NextResponse.rewrite(`${endpoint}/${path}`)
    }
}

โค้ดนี้ทำงานได้สำหรับวิธี GET แต่ไม่ทำงานสำหรับวิธี POST (เซิร์ฟเวอร์ภายในไม่ได้รับร่างคำขอ)

เมื่อฉันเขียน rewrite ใน next.config.js มันทำงาน

async rewrites() {
    return [
        {
            source: "/api/:path*",
            destination: `${process.env.API_ENDPOINT}/:path*`,
        },
    ]
},

ฉันจะทำให้มันทำงานโดยใช้ NextJS middleware ได้อย่างไร?

ฉันจำเป็นต้องใช้ NextJS middleware เพื่อเพิ่ม headers เพิ่มเติมให้กับคำขอ และวิธี next.config.js นั้นก็ไม่สามารถใช้ได้เช่นกันเมื่อฉันสร้างฟังก์ชัน middleware (แม้ว่าฟังก์ชันนั้นจะไม่ทำอะไรเลยก็ตาม)