【问题标题】:Custom Next.js - difference between getRequestHandler and render functions自定义 Next.js - getRequestHandler 和渲染函数之间的区别
【发布时间】:2020-05-15 05:18:55
【问题描述】:

早安,

我很惊讶我找不到任何关于 next 包的 getRequestHandlerrender 函数的信息。

我正在尝试设置自定义服务器,并且想知道 render 函数实际上在做什么,或者为什么要使用它? getRequestHandler 清楚地呈现了应用程序,那么我为什么要使用 render 手动传递路径?另外,分别传入路径名和查询有什么意义?

我显然对这两个的用例感到困惑 - 在哪种情况下我会使用其中一个?

感谢大家的帮助。

阿纳尼

https://nextjs.org/docs/advanced-features/custom-server

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  createServer((req, res) => {
    // Be sure to pass `true` as the second argument to `url.parse`.
    // This tells it to parse the query portion of the URL.
    const parsedUrl = parse(req.url, true)
    const { pathname, query } = parsedUrl

    if (pathname === '/a') {
      app.render(req, res, '/b', query)
    } else if (pathname === '/b') {
      app.render(req, res, '/a', query)
    } else {
      handle(req, res, parsedUrl)
    }
  }).listen(3000, err => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})

【问题讨论】:

    标签: javascript node.js next.js


    【解决方案1】:

    getRequestHandler 与渲染

    app.getRequestHandler 返回一个请求处理程序,我们可以使用它来解析所有 HTTP 请求。 app.render 检查是否需要提供静态资产。它还检查请求的页面是否是被阻止/内部页面。在这些检查通过后,Next.js 也使用我们将从app.getRequestHandler 获得的相同请求处理程序。如果我们直接使用请求处理程序,我们将不会得到这些检查并遇到需要手动处理的问题。

    这里是处理自定义服务器的部分源代码。我希望它能让答案更清楚一点。

    // next/next-server/server/next-server.ts
    // This function expose a private method, which used by render 
    public getRequestHandler() {
      return this.handleRequest.bind(this)
    }
    
    // render method
    public async render() {
      // .... more code
      // check if server needs to handle static files
      if (
        !query._nextDataReq &&
        (url.match(/^\/_next\//) ||
          (this.hasStaticDir && url.match(/^\/static\//)))
      ) {
        return this.handleRequest(req, res, parsedUrl)
      }
      // check the requested page is a internal/blocked page
      if (isBlockedPage(pathname)) {
        return this.render404(req, res, parsedUrl)
      }
    
      const html = await this.renderToHTML(req, res, pathname, query)
      // Request was ended by the user
      if (html === null) {
        return
      }
    
      // respond with rendered HTML
      return this.sendHTML(req, res, html)
    
    }
    

    路径和查询

    我认为 Next.js query 与 URL 查询字符串有点不同。您可以拥有像 '/a' 这样的路由并传入查询对象,而无需将这些查询添加到您的 URL。

    这是我回答问题的最大努力。希望我能提供一些帮助。

    参考:

    https://github.com/vercel/next.js/blob/canary/packages/next/next-server/server/next-server.ts

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-30
      • 1970-01-01
      • 2011-12-20
      • 2019-06-09
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      • 2016-06-01
      相关资源
      最近更新 更多