您可以通过此博客开始了解最佳实践和文件结构
应用程序的入口点应该这样定义
// This will be our application entry. We'll setup our server here.
const http = require('http');
const app = require('../app'); // The express app we just created
const port = parseInt(process.env.PORT, 10) || 8000;
app.set('port', port);
const server = http.createServer(app);
server.listen(port);
在这种情况下,您只能启动express服务器。
https://scotch.io/tutorials/getting-started-with-node-express-and-postgres-using-sequelize
你的应用程序的文件夹结构应该是这样的,你可以根据自己的方便进行自定义,但应该类似于此
âââ app.js
âââ bin
â âââ www
âââ package.json
âââ server
âââ config
â âââ config.json
âââ migrations
âââ models
â âââ index.js
âââ seeders
现在您的模型文件夹将包含所有数据库模型。
const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Require our routes into the application.
require('./server/routes')(app);
app.get('*', (req, res) => res.status(200).send({
message: 'Welcome to the beginning of nothingness.',
}));
module.exports = app;
要编写控制器,应该在控制器中导入模型。
const Todo = require('../models').Todo;
module.exports = {
create(req, res) {
return Todo
.create({
title: req.body.title,
})
.then(todo => res.status(201).send(todo))
.catch(error => res.status(400).send(error));
},
};