users.js
var express = require('express');
var router = express.Router();
router.get('/users', function(req, res, next) {
res.send('Test')
});
module.exports = router;
index.js
var express = require('express');
var router = express.Router();
var users = require('./users')
...
app.js
...
var index = require('./routes/index');
app.use('/', index);
...
这里我只列出部分代码,但无论我是在index.js中引用user.js还是在app.js中引用,处理/users这个网络请求都是404,所以我想问一下是不是因为一个项目中只能建立一个路由啊,然后另一个问题就是app.use()这个函数的参数分别代表了什么,谢谢各位大神
In the entry file, such as app.js, you usually register middleware, etc., export the app, and then directly introduce the app into the routing file you need to use, such as app.get("/hello" , function() {})
The use function has two parameters. The first parameter usually matches a route, and the second function registers the middleware. If there is no first parameter, then the second function will be applied to every request.
Looking at the meaning of the question, users.js is referenced in index.js. I guess I want to have a unified routing manager and don’t want to register all routes in app.js because there is no complete code in index.js. , so following this idea, the content of index.js is like this:
var express = require('express');
var users=require('./users');
var app=express();
app. use('/user',users);
module.exports=app;
Then just register this index.js in the same entrance app.js, so you don’t have to register the users route anymore