[英]Separate express api database from server.js file
I'm very newbie to Node.js and so is this question. 我是Node.js的新手,所以这个问题也是如此。
Im using this example please take a look at this link below. 我正在使用此示例,请在下面查看此链接。
https://github.com/sahat/newedenfaces-react/blob/master/server.js https://github.com/sahat/newedenfaces-react/blob/master/server.js
In this server.js file the programmer is making call to 在此server.js文件中,程序员正在调用
mongoose.connect(config.database);
app.get('/api/characters', function(req, res, next) {}
etc 等等
all in server.js file 全部在server.js文件中
I want to keep everything cleaner 我要保持一切清洁
and just do the 然后做
server.listen(app.get('port'), function() {}
on server.js
file and the rest of the things on some different file and import or stuff them. 在server.js
文件上,将其余内容放在其他文件上,然后导入或填充它们。
Thanks. 谢谢。
If you use the express cli generator ( https://expressjs.com/en/starter/generator.html ) to generate a project, you will see there how by default express separates api logic from the app.js (= your server.js file). 如果您使用express cli生成器( https://expressjs.com/en/starter/generator.html )生成项目,则将看到默认情况下express如何将api逻辑与app.js(=服务器)分开。 js文件)。
You have to declare in your app.js where specific logic for a controller is stored 您必须在app.js中声明存储控制器的特定逻辑的位置
var users = require('./routes/users');
And then which route should be used for that controller. 然后应该为该控制器使用哪个路由。
app.use('/users', users);
Then you can create a file there called users.js and put your logic there like here ( users.js ) 然后,您可以在其中创建一个名为users.js的文件,并将逻辑放在此处( users.js )
var express = require('express');
var router = express.Router();
/* this is the route "/users/" as "/users" is defined in app.js to use that controller and / is defined here */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
Next if you want to store youre DB stuff in an extra file you can create a models folder to declare your schema (if you use mongoose): 接下来,如果要将数据库内容存储在一个额外的文件中,则可以创建一个models文件夹来声明您的模式(如果使用mongoose):
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
firstName: {type: String, required: true},
lastName: {type: String, required: true},
email: {type: String, required: true, unique: true},
});
module.exports = mongoose.model('User', schema);
Then you can import it to your users routes files 然后可以将其导入到用户的路由文件中
var User = require('../models/user');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.