1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00
next.js/examples/pass-server-data/server.js
Chris 7afc008aa7 Example: Passing data from server through API (#2594)
* Add example on how to pass data through js api during SSR

Requested in #1117

* Use content negotiation instead of a separate route

* Codereview feedback

* Move security related test cases into a its own file.

* Removes the unused renderScript function

* Add a nerv example. (#3573)

* Add a nerv example.

* Fix for indentation/style

* Fix for name
2018-02-03 17:11:47 +01:00

40 lines
1 KiB
JavaScript

const express = require('express')
const next = require('next')
const api = require('./operations/get-item')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
// Set up home page as a simple render of the page.
server.get('/', (req, res) => {
console.log('Render home page')
return app.render(req, res, '/', req.query)
})
// Serve the item webpage with next.js as the renderer
server.get('/item', (req, res) => {
const itemData = api.getItem()
app.render(req, res, '/item', { itemData })
})
// When rendering client-side, we will request the same data from this route
server.get('/_data/item', (req, res) => {
const itemData = api.getItem()
res.json(itemData)
})
// Fall-back on other next.js assets.
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(3000, (err) => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
})