I’m a newbie and I have some questions about node.
My app.js looks like this:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//api
var a_api = require('./routes/api/a');
var b_api = require('./routes/api/b');
var c_api = require('./routes/api/c');
var d_api = require('./routes/api/d');
app.use('/api', [a_api, b_api, c_api, d_api]);
a.js
var express = require('express');
var router = express.Router();
var async = require('async');
router.get('/:id/:name/home', function (req, res, next) {
var id = req.params.id;
var name = req.params.name;
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({'id':id,'name':name}));
});
module.exports = router;
Assuming that there are 100 routing interfaces now, don’t I need to require 100 files in the app and then configure them in use 100 times? I always feel that the writing is wrong. If I want to write a static loader, how should I write it? ?
The following is my personal opinion:
1.app.js is a service startup file and should not deal with routes (routes) too much. Taking the picture of the subject as an example, every time I want to add a new route, I need to Modify app.js, and app.js will become longer and longer
2. Attached is my solution to this problem
3. Hope this helps the topic owner
Your routing should be divided into modules.
Generally one module and one js
User module user.js /users/xxx
Order module order.js /order/xxx
...
Even if you have 100 URLs, generally speaking, there will not be many modules. 10 modules is no longer a small system. It looks good when you write it like this
tips:
express sends json
App.js generally writes the first part of the url, and writes the remaining part in specific js. For example, a url is localhost:3000/use/index. For this url, you can write the use part of the url in app.js , the index part is written in a specific js, such as a.js, then the writing method in app.js is app.use('use',a), and then write router.get('/index', fn), when designing the URL, you can design a fixed first half of the URL, such as /use/index, /use/login, etc., and fix the use, so that only one needs to be written in app.js.