nextJS 13 中的重定向(中间件)

Bla*_*021 1 middleware next.js

我正在开发我的中间件,我想在用户登录后重定向用户。问题是 api 没有到达终点并且卡在中间件部分(根据我的观察)并且页面也没有重定向。

import { NextRequest, NextResponse } from "next/server";

export function middleware(req) {
  const url = req.url;

  if (url.includes("login")) {
    return NextResponse.redirect("localhost:3000/home", req.url);
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/", "/api/login"],
};
Run Code Online (Sandbox Code Playgroud)

小智 5

所以NextResponse.redirect()不将字符串作为第二个参数。

我认为您正在寻找更像这样的东西:

import { NextResponse } from 'next/server';

NextResponse.redirect(new URL('/home', req.url));
Run Code Online (Sandbox Code Playgroud)

这将构造一个新的 URL 对象,并创建 URL https://localhost:3000/home。

NextResponse.redirect()

生成重定向到 URL 的响应。在方法中使用之前可以创建和修改 URL NextResponse.redirect()。例如,您可以使用该 request.nextUrl属性获取当前 URL,然后修改它以重定向到不同的 URL。

来自Next.js 文档

网址:

URL 接口用于解析、构造、规范化和编码 URL。它的工作原理是提供允许您轻松读取和修改 URL 组成部分的属性。

const url = new URL("../cats", "http://www.example.com/dogs");
console.log(url.hostname); // "www.example.com"
console.log(url.pathname); // "/cats"
Run Code Online (Sandbox Code Playgroud)

来自MDN 网络文档