【问题标题】:How to get generated HTML as string in Next.js custom server?如何在 Next.js 自定义服务器中获取生成的 HTML 作为字符串?
【发布时间】:2021-11-21 04:22:49
【问题描述】:

我有一个渲染 React 组件的 SSR API。我需要将呈现的 HTML 作为字符串获取,以便我可以对其进行操作并将其与其他信息一起发送回 JSON 对象。

在 Next.js 中,我使用的是自定义服务器。如何获取 HTML 作为变量中的字符串?

// server.js
const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')

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

app.prepare().then(() => {
  createServer((req, res) => {
    const parsedUrl = parse(req.url, true)
    const { pathname, query } = parsedUrl

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

我尝试使用render 函数和renderToHTML 函数,但无法获取呈现的字符串。我真的不明白 render 函数在后台做了什么。

关于如何实现这一点的任何线索?

【问题讨论】:

  • “我如何将 HTML 作为字符串获取” - 澄清一下,您是指 Next.js 生成的 HTML 吗?
  • 没错,由 Next.js 生成

标签: node.js reactjs next.js server-side-rendering


【解决方案1】:

您可以覆盖 res.end 并捕获 Next.js 传递给它的生成的 HTML。注意res.end 是在app.render 之后调用的。

if (pathname === '/a') {
    const resEnd = res.end.bind(res) // Save original `res.end` into a variable to be called later
    res.end = (html) => {
        console.log(html) // Manipulate the HTML as you like
        resEnd(html)
        return
    }
    app.render(req, res, '/a', query)
} 

【讨论】:

    猜你喜欢
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 2016-04-05
    • 2022-11-19
    相关资源
    最近更新 更多