reactjs Next.js中间件重写/重定向

bnlyeluc  于 2023-03-29  发布在  React
关注(0)|答案(1)|浏览(180)

由于某种原因,出现无效url错误
index.tsx

import checkAuth from "@/Middleware/checkAuth";
export async function getServerSideProps({req}) {
    checkAuth(req)
    return {
      props: {}, // will be passed to the page component as props
    }
  }
export default function HomeAdmin() {
    return (<div className='adminPanel'>
    </div>)
}

checkAuth.ts

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

export default function checkAuth(req:NextRequest) {
    console.log(req.nextUrl);
    return NextResponse.redirect(new URL('/', req.url))
    // return NextResponse.rewrite(new URL('/', req.url))
}

无效url错误还请求。nextUrl始终未定义
我在localhost\ip\domen上试过了没有区别,总是有一个url错误

l7mqbcuq

l7mqbcuq1#

next@^13中,您可能会遇到类似的情况。这是一个中间件示例,但同样的概念应该适用。

export function middleware(request: NextRequest) {

    const updatedUrl = request.nextUrl.clone();
    updatedUrl.protocol = 'https:';
    updatedUrl.host = 'www.proxied-host.com';
    updatedUrl.port = '';

    return NextResponse.rewrite(updatedUrl);
}

相关问题