NextJs跨域的两种方式

2,683 阅读1分钟

本次使用的NextJs版本是13.5.4,NextJs一般支持两种方式跨域,一种是修改next.config.js配置文件,一种是使用middleware。

配置next.config.js

/** @type {import('next').NextConfig} */

const nextConfig = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: `${process.env.HOST}/:path*`
      },
    ]
  }
}

module.exports = nextConfig

middleware允许您在请求完成之前运行代码。然后,根据传入的请求,您可以通过重写、重定向、修改请求或响应标头或直接响应来修改响应。

配置middleware.js

import { NextResponse } from 'next/server';
 
// This function can be marked `async` if using `await` inside
export function middleware(request) {
  if (request.nextUrl.pathname.startsWith('/api')) {

    const hostname = process.env.HOST

    const requestHeaders = new Headers(request.headers)
    requestHeaders.set('host', hostname)

    let url = request.nextUrl.clone()
    // url.protocol = 'https'
    url.hostname = hostname
    url.port = process.env.HOSTPORT
    url.pathname = url.pathname.replace(/^\/api/, '');

    return NextResponse.rewrite(url, {
      headers: requestHeaders,
    })
  }
}
 
export const config = {
  matcher: '/api/:path*',
}