render.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { ssrMiddleware } from 'quasar/wrappers'
  2. // This middleware should execute as last one
  3. // since it captures everything and tries to
  4. // render the page with Vue
  5. const logRequest = process.env.LOG_REQUEST === 'true'
  6. export default ssrMiddleware(({ app, resolve, render, serve }) => {
  7. // we capture any other Express route and hand it
  8. // over to Vue and Vue Router to render our page
  9. app.get(resolve.urlPath('*'), (req, res) => {
  10. const reqTimestamp = Date.now()
  11. if (logRequest) {
  12. console.log('req timestamp: ' + reqTimestamp + ' ----> ', {
  13. url: req.url,
  14. method: req.method,
  15. rawHeaders: req.rawHeaders
  16. })
  17. }
  18. res.setHeader('Content-Type', 'text/html')
  19. render(/* the ssrContext: */ { req, res })
  20. .then(html => {
  21. // now let's send the rendered html to the client
  22. res.send(html)
  23. if (logRequest) {
  24. console.log('res timestamp: ' + Date.now() + ' ----> ', {
  25. reqTimestamp: reqTimestamp,
  26. statusCode: res.statusCode,
  27. url: res.req.url,
  28. method: res.req.method,
  29. _header: res._header
  30. })
  31. }
  32. })
  33. .catch(err => {
  34. // oops, we had an error while rendering the page
  35. // we were told to redirect to another URL
  36. if (err.url) {
  37. if (err.code) {
  38. res.redirect(err.code, err.url)
  39. } else {
  40. res.redirect(err.url)
  41. }
  42. } else if (err.code === 404) {
  43. // hmm, Vue Router could not find the requested route
  44. // Should reach here only if no "catch-all" route
  45. // is defined in /src/routes
  46. res.status(404).send('404 | Page Not Found')
  47. } else if (process.env.DEV) {
  48. // well, we treat any other code as error;
  49. // if we're in dev mode, then we can use Quasar CLI
  50. // to display a nice error page that contains the stack
  51. // and other useful information
  52. // serve.error is available on dev only
  53. serve.error({ err, req, res })
  54. } else {
  55. // we're in production, so we should have another method
  56. // to display something to the client when we encounter an error
  57. // (for security reasons, it's not ok to display the same wealth
  58. // of information as we do in development)
  59. // Render Error Page on production or
  60. // create a route (/src/routes) for an error page and redirect to it
  61. res.status(500).send('500 | Internal Server Error')
  62. console.error(err.stack)
  63. }
  64. })
  65. })
  66. })