中间件

NextJS的中间件工作在服务端,可以起到拦截路由请求的作用,通过中间件我们可以实现登陆拦截、记录日志等功能。

编写中间件

中间件需要定义在middleware.js文件中,它需要放置在工程根目录(这里不要搞错,不是app目录)。下面代码是一个最简单的中间件实现,该中间件拦截/api开头的请求,具体的处理逻辑仅仅是打印一条日志。

middleware.js

import { NextResponse } from "next/server";

export const middleware = async (request) => {
  console.log("收到请求");
  const response = NextResponse.next();
  return response;
};

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

具体来说,中间件拦截的路径是通过导出config对象来设置的,上面代码中/api/:path*也可以写作/about/(.*),表示拦截所有/api开头的路由。此外config对象也可以设置为一个数组,例如["/home/:path*", "/dashboard/:path*"]

在中间件中读写请求和响应数据

中间件可以读取请求数据,以及修改响应数据,下面是一些例子。

middleware.js

import { NextResponse } from "next/server";
import { cookies, headers } from "next/headers";

export const middleware = async (request) => {
  // 读取Cookie
  const cookie = cookies().get("user");
  console.log(cookie);
  // 读取Header
  const header = headers().get("User-Agent");
  console.log(header);

  const response = NextResponse.next();

  // 设置Cookie
  response.cookies.set("user", "Tom");
  // 设置Header
  response.headers.set("Token", "abc123");

  return response;
};

export const config = {
  matcher: "/api/:path*",
};
作者:Gacfox
版权声明:本网站为非盈利性质,文章如非特殊说明均为原创,版权遵循知识共享协议CC BY-NC-ND 4.0进行授权,转载必须署名,禁止用于商业目的或演绎修改后转载。
Copyright © 2017-2024 Gacfox All Rights Reserved.
Build with NextJS | Sitemap