繁体   English   中英

使用中间件时,客户端未定义 getServerSideProps 道具

[英]getServerSideProps props are undefined on client-side when using middleware

如果使用 Nextjs 中间件满足特定条件,我将尝试在每个页面上进行重定向。

出于某种原因,每当 middleware.ts 中的matcher匹配页面时,该页面上getServerSideProps的所有道具在到达客户端时都是undefined 当我从matcher正则表达式中删除页面时,它们会按预期使用正确的值工作。

中间件.ts

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export default async function middleware(req: NextRequest) {
  return NextResponse.next();
}

export const config = {
  matcher: ['/(tag|about)(.)*'],
};

我如何确保getServerSideProps仍然在同样触发middleware function 的页面上触发?

getServerSideProps正在触发,我在终端中看到了正确的值,但我在客户端仍然没有undefined

在此处输入图像描述

将 middleware.ts 移动到正确的位置,只会在 /tag|about 页面上运行

|-- pages/
│   ├── tag/
│   │   ├── index.js
│   │   └── middlware.js

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
 
// This function can be marked `async` if using `await` inside
export default async function middleware(req: NextRequest) {
 if (request.nextUrl.pathname) {
  return await NextResponse.redirect(new URL('/home', request.url))
 }

 return NextResponse.next()
  
}
 
export const config = {
  matcher: ['/(tag|about)(.)*'],
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM