自定义服务器 nextjs 和 nodejs 的路由问题

时间:2021-02-07 20:57:23

标签: node.js express next.js

我有一个客户,他有一个博客的仪表板网站,每个仪表板页面都由 nodejs 渲染...(ejs)

 ///EXPRESS ROUTES //DASHBOARD
  app.get('/error', (req, res) => {
    return res.render('pages/error/404')
  })
  app.get("/admin",isAuthenticated, (req, res) => {
    return res.render("index");
  });

他正在询问使用 nextjs 作为前端(渲染帖子)以帮助他进行 SEO(他不想使用 nextjs 构建仪表板)

我尝试使用 Nextjs-custom-server 示例并制作一个混合应用

const express = require('express')
const next = require('next')
const dev = false
const nextServer = next({ dev })
const handle = nextServer.getRequestHandler()

nextServer.prepare().then(() => {
  const app = express()
  app.use(bodyParser.urlencoded({ extended: true }))
  app.use(bodyParser.json())
  app.set("view engine", "ejs");
  app.use(express.static(__dirname + "/public"));
  app.use(morgan("dev"));
  app.use(express.urlencoded({ extended: true }));
// Middlewares
app.use(cookieParser());
// MongoDB
const mongoUrl = `URI HERE`
PORT = process.env.PORT || 3000;
mongoose
.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true})
.then(() => {
  ///EXPRESS ROUTES //DASHBOARD
  app.get('/error', (req, res) => {
    return res.render('pages/error/404')
  })
  app.get("/admin",isAuthenticated, (req, res) => {
    return res.render("index");
  });
  app.use(userRouter);

  ///NEXT ROUTES   //BLOG
  app.get('/a', (req, res) => {
    return nextServer.render(req, res, '/a', req.query)
  })
  app.get('/b', (req, res) => {
    return nextServer.render(req, res, '/b', req.query)
  })
  app.all('*', (req, res) => {
    return handle(req, res)
  })
  app.listen(port, (err) => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})
})

它在本地主机上按预期运行 https://media0.giphy.com/media/S3nVx84NK3IZW3Zczs/giphy.gif

但是当我将它部署到 Vercel 时,nodejs 路由不起作用 https://media0.giphy.com/media/vMeHEtFsieTQJgNmuG/giphy.gif

我知道我遗漏了什么或混淆了一个重要的概念。 我在想

1- 将仪表板托管到例如dashboard.com

和 nextjs 作为前端,例如 myblog.com

没有人愿意拥有两个不同的网站

2- 如果可能,将仪表板托管到子域dashboard.myblog.com 和 nextjs 到域 myblog.com

3- 使用仪表板(它是一个 nodejs 应用程序)而不是 nextjs api 但是如果它在 nextjs pages/api/index.js 中,nodejs 可以渲染页面吗?

我该如何解决这个冲突? 感谢您的时间和耐心

0 个答案:

没有答案