DWQA QuestionsCategory: Development ToolHow express 4. X processes router requests in different JS files
TimGary asked 1 month ago

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);
...

I’ll just list some of the code here, but whether I’m in index.js Quoted in user.js Is it still there app.js It is 404 to handle the network request of / users, so I would like to ask whether it is because only one route can be established in a project app.use () what do the parameters of this function represent? Thank you

2 Answers
Yin Guangyao answered 1 month ago

clipboard.png
In the entry file, for example app.js In general, it is necessary to register middleware, export the app, and then directly import 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 generally matches a route. The second function registers the middleware. If there is no first parameter, the second function will be applied to every request.

Cloud language 2019 answered 1 month ago

Look at the meaning of the problem index.js Is cited in users.js I guess we want to have a unified routing manager, but we don’t want to have a unified routing manager app.js It registers all routes because index.js There is no complete code in, so follow this line of thinking, index.js The content is as follows:
var express = require(‘express’);
var users=require(‘./users’);
var app=express();
app.use(‘/user’,users);
module.exports=app;
And then at the same entrance app.js Register this in it index.js That’s it. You don’t have to register the users route