【发布时间】:2017-06-19 14:27:16
【问题描述】:
简介
到目前为止,我有三个文件,一个test.js 是一个文件,我在其中构建了三个可以工作的函数。
但现在我正在尝试使用 MVC 或至少某种模式来构建结构。所以现在我router.js 和app.js
问题
我是否应该将来自 test.js 的 promise 函数放入我的 config.js 或 server.js 或其他东西中,我只是对人们如何做到这一点以及构建 NodeJS 的正确方法感兴趣。
- server.js
在这里启动服务器并将路由应用到我的应用程序
var configure = require('./router');
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
// get an instance of router
var router = express.Router();
configure(router);
app.listen(port);
console.log('Server has started!! ' + port);
// apply the routes to our application
app.use('/', router);
- config.js
在这里我建立我的路线
module.exports = function (router) {
// route middleware that will happen on every request
router.use(function (req, res, next) {
// log each request to the console
console.log(req.method, req.url);
// continue doing what we were doing and go to the route
next();
});
// home page route (http://localhost:8080)
router.get('/', function (req, res) {
res.send('im the home page!');
});
// sample route with a route the way we're used to seeing it
router.get('/sample', function (req, res) {
res.send('this is a sample!');
});
// about page route (http://localhost:8080/about)
router.get('/about', function (req, res) {
res.send('im the about page!');
});
// route middleware to validate :name
router.param('name', function (req, res, next, name) {
// do validation on name here
console.log('doing name validations on ' + name);
// once validation is done save the new item in the req
req.name = name;
// go to the next thing
next();
});
// route with parameters (http://localhost:8080/hello/:name)
router.get('/hello/:name', function (req, res) {
res.send('hello ' + req.params.name + '!');
})
// app.route('/login')
// show the form (GET http://localhost:8080/login)
.get('/login', function (req, res) {
res.send('this is the login form');
})
// process the form (POST http://localhost:8080/login)
.post('/login', function (req, res) {
console.log('processing'); // shows on console when post is made
res.send('processing the login form!'); // output on postman
});
};
- test.js
这里是一系列函数,它们是获取数据和 API 密钥的承诺链
(小函数,多个函数之一)
var firstFunction = function () {
return new Promise (function (resolve) {
setTimeout(function () {
app.post('/back-end/test', function (req, res) {
console.log(req.body);
var login = req.body.LoginEmail;
res.send(login);
resolve({
data_login_email: login
});
});
console.error("First done");
}, 2000);
});
};
【问题讨论】:
-
实际上你的 config.js 根本不是配置,而是路由。所以称它们为 routes.js 并将 express.Router 直接导入 router.js 而不是传递它。
-
知识加分,谢谢
-
更好地使用官方文档中的这种方法expressjs.com/en/guide/routing.html#express-router
-
感谢@jstice4all 现在调查
标签: javascript node.js express design-patterns model-view-controller