Unverified Commit 6c5efd7b authored by xliusstk's avatar xliusstk Committed by GitHub

Fix ssr-caching example (#12180)

cacheable-response.get expects a get(req, res) method signature:
https://www.npmjs.com/package/cacheable-response#get

Before the change:
```
curl -s  -v http://localhost:3000/blog/first 2>&1 | grep HTTP/1.1
> GET /blog/first HTTP/1.1
< HTTP/1.1 404 Not Found
```
After the change:
```
curl -s  -v http://localhost:3000/blog/first 2>&1 | grep HTTP/1.1
> GET /blog/first HTTP/1.1
< HTTP/1.1 200 OK
```

This is a partial fix of https://github.com/zeit/next.js/issues/12019 to make the example work. However it doesn't fix the error 
```
(node:62360) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
``` , which will need a change at server/next-server.ts

See related issue:
https://github.com/zeit/next.js/discussions/11525 
https://github.com/zeit/next.js/issues/11665
parent 0b947562
...@@ -10,8 +10,11 @@ const handle = app.getRequestHandler() ...@@ -10,8 +10,11 @@ const handle = app.getRequestHandler()
const ssrCache = cacheableResponse({ const ssrCache = cacheableResponse({
ttl: 1000 * 60 * 60, // 1hour ttl: 1000 * 60 * 60, // 1hour
get: async ({ req, res, pagePath, queryParams }) => { get: async ({ req, res }) => {
const data = await app.renderToHTML(req, res, pagePath, queryParams) const data = await app.renderToHTML(req, res, req.path, {
...req.query,
...req.params,
})
// Add here custom logic for when you do not want to cache the page, for // Add here custom logic for when you do not want to cache the page, for
// example when the page returns a 404 status code: // example when the page returns a 404 status code:
...@@ -28,12 +31,10 @@ const ssrCache = cacheableResponse({ ...@@ -28,12 +31,10 @@ const ssrCache = cacheableResponse({
app.prepare().then(() => { app.prepare().then(() => {
const server = express() const server = express()
server.get('/', (req, res) => ssrCache({ req, res, pagePath: '/' })) server.get('/', (req, res) => ssrCache({ req, res }))
server.get('/blog/:id', (req, res) => { server.get('/blog/:id', (req, res) => {
const queryParams = { id: req.params.id } return ssrCache({ req, res })
const pagePath = '/blog'
return ssrCache({ req, res, pagePath, queryParams })
}) })
server.get('*', (req, res) => handle(req, res)) server.get('*', (req, res) => handle(req, res))
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment