正確的結構到目前爲止,我有三個文件,一個test.js
是我已經建立了合作三大功能的文件。
但現在我正在嘗試使用MVC或至少某種模式的結構。所以,現在我router.js
和app.js
問題
我應該把我的諾言功能從test.js
我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
- test.js
在她e口建立我路由
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
});
};
在這裏是那些承諾獲取數據和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根本不是configs,而是路由。所以稱它們爲routes.js並直接將express.Router導入到router.js而不是傳遞它。 – jstice4all
加1爲知識,謝謝 – Beep
更好地使用這種方法從官方文檔https://expressjs.com/zh/guide/routing.html#express-router – jstice4all