node.js - express 4.x 如何在不同js文件中处理router请求
怪我咯
怪我咯 2017-04-17 16:11:40
0
2
308

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()这个函数的参数分别代表了什么,谢谢各位大神

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(2)
大家讲道理

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template