简体   繁体   English

给定用户对索引页('/')的请求,我们如何在 Next.js 中的服务器上拦截并运行 function?

[英]Given a user's request for the index page ('/'), how do we intercept and run a function on the server in Next.js?

Is there a way using a middleware function or some other method in Next.js to see if a user is attempting to go to the home page?有没有办法在 Next.js 中使用中间件 function 或其他方法来查看用户是否正在尝试将 go 转到主页?

What I'm trying to do basically is intercept a user's request for the home page.我要做的基本上是拦截用户对主页的请求。 Intercepting a URL request is relatively easy to do with Next.js middleware.使用 Next.js 中间件拦截 URL 请求相对容易。 For example, if you want to see if a user is trying to access a single page called /login , you can access the request url like so:例如,如果您想查看用户是否正在尝试访问名为/login的单个页面,您可以访问请求 url ,如下所示:

export default async function middleware(req, res){

   const url = req.url;

   if (url.includes('/login')){
       // carry out action
   }

}

However, how can this be done for a home page URL (eg https://fakewebsite.com/ or in development, localhost:3000)?但是,对于主页 URL(例如https://fakewebsite.com/或正在开发中的 localhost:3000)如何做到这一点?

I think you can use the middleware introduced in nextjs version 12 to accomplish this.我认为您可以使用 nextjs 版本 12 中引入的中间件来完成此操作。 There you can introduce a config for matching URLs and have access to user's request: Next.JS middleware .在那里,您可以引入匹配 URL 的配置并访问用户的请求: Next.JS 中间件

The problem with what you have is that you're missing the config export from your middleware, inside which you can specify the matcher :您所拥有的问题是您缺少中间件的config导出,您可以在其中指定matcher

// middleware.js

export const config = {
  matcher: '/',
}

This will only allow home requests to reach your middleware.这将只允许home请求到达您的中间件。

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

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