简体   繁体   中英

NextJs API: respond with SSR react page

Goal:

  • Respond with server side rendered html from nextjs api

Why i need this:

  • I am building custom internal html page editor using react where the page model is represented as JSON. I want to send a page model JSON to the nextjs api, pass it to react component and get the html back.

What i've tried is the api with direct call to ReactDOMServer.renderToString :

export default (req, res) => {

  const model = req.body.pageModel

  const body = ReactDOMServer.renderToString(
      <App
        model={model}
      />)

  res.statusCode = HttpStatus.OK
  res.setHeader("Content-Type", "text/html")
  res.end(`
  <!DOCTYPE html>
  <html >
    <head></head>
    <body>
        ${body}
    </body>
  </html>
`)
}

Question:

Is there a way to reuse nextjs rendering approach instead of ReactDOMServer.renderToString and JS string templates so that i am able to specify and use my own _app.js and _page.js in response to api?

Something like following will suit my needs:

const html = next.render(<App model={model}>)
res.end(html)

If you're open to ready-to-use solutions, I recommend to look into React rich editors, https://draftjs.org/ being the most popular. They come with a collection of functions and particularly what you need and HTML compatibility.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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