app.js
const express = require('express');
const next = require('next');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app
.prepare()
.then(() => {
const server = express();
const indexRouter = require('./routes/indexRouter');
server.use(indexRouter);
server.all('*', (req, res) => {
return handle(req, res);
});
server.listen(port, (err) => {
if (err) throw err;
console.log('> Ready on http://localhost:' + port);
});
})
.catch((ex) => {
console.error(ex.stack);
process.exit(1);
});
indexRoutes.js
const express = require('express');
const router = express.Router();
const userController = require('../controllers/user');
router.post('/api/signup', userController.signup);
我想通过 indexRoutes.js 中的 nextjs 渲染组件。我在主 app.js 中看到其他人做了
server.get('/login', (req, res) => {
app.render(req, res, '/login');
});
但我不明白如何在单独的文件中进行。我尝试这样做,但没有结果。
indexRoutes.js
const express = require('express');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const router = express.Router();
const userController = require('../controllers/user');
router.post('/api/signup', userController.signup);
router.get('/login', (req, res) => {
return app.render(req, res, '/login'); // this does not work
});
我该如何解决我的问题?
答案 0 :(得分:1)
如果您想将路由放在单独的文件中,您可以创建以下 indexRouter.js
文件:
// routes/indexRouter.js
const userController = require('../controllers/user');
const indexRouter = (server, app) => {
server.post('/api/signup', userController.signup);
server.get('/login', (req, res) => {
return app.render(req, res, '/login');
});
};
module.exports = indexRouter;
然后您可以从 app.js
请求它并将 server
和 app
对象传递给它。
// app.js
// ...
app
.prepare()
.then(() => {
const server = express();
const indexRouter = require('./routes/indexRouter');
indexRouter(server, app)
server.all('*', (req, res) => {
return handle(req, res);
});
server.listen(port, (err) => {
if (err) throw err;
console.log('> Ready on http://localhost:' + port);
});
})
.catch((ex) => {
console.error(ex.stack);
process.exit(1);
});