英文:
Redirect in nextJS 13 (Middleware)
问题
我正在处理我的中间件,我想要在用户登录后重定向他们。问题在于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"],
};
英文:
I am working on my middleware, and I want to redirect the user once they logged in. Issue is that the api is not hitting the end point and is stuck in the middleware section (as per my observation) and the page is not redirecting too.
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"],
};
答案1
得分: 2
所以 NextResponse.redirect()
不接受字符串作为其第二个参数。
我认为你正在寻找类似这样的东西:
import { NextResponse } from 'next/server';
NextResponse.redirect(new URL('/home', req.url));
这将构建一个新的URL对象,并且会创建url https://localhost:3000/home。
NextResponse.redirect():
> 生成重定向到URL的响应。
> 可以在使用NextResponse.redirect()
方法之前创建和修改URL。例如,你可以使用request.nextUrl
属性获取当前URL,然后修改它以重定向到不同的URL。
来自Next.js文档。
URL:
> 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"
来自MDN Web文档。
英文:
So NextResponse.redirect()
does not take a string as its second parameter.
I think you are looking for something more like this:
import { NextResponse } from 'next/server';
NextResponse.redirect(new URL('/home', req.url));
This would construct a new URL object, and that would create the url https://localhost:3000/home.
NextResponse.redirect():
> Produce a response that redirects to a URL.
> The URL can be created and modified before being used in the
> NextResponse.redirect()
method. For example, you can use the
> request.nextUrl
property to get the current URL, and then modify it
> to redirect to a different URL.
from Next.js Docs.
The URL:
> The URL interface is used to parse, construct, normalize, and encode
> URLs. It works by providing properties which allow you to easily read
> and modify the components of a URL.
const url = new URL("../cats", "http://www.example.com/dogs");
console.log(url.hostname); // "www.example.com"
console.log(url.pathname); // "/cats"
from MDN Web Docs.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论