[英]How can I set the routes correctly?
Here is a sample code: 这是一个示例代码:
var x = require('./folder/usefile');
var Auth = passport.authenticate('jwt', { session: false });
module.exports = function(app){
console.log('inside function(app)'); //line 1 executed!
var player = express.Router();
var finalRun = express.Router();
app.use('/api/usefile',player);
player.get('/', Auth, x.login);
player.post('/post', Auth, function(req, res){
x.register});
app.use('/api',finalRun);
console.log('inside api'); //line 2 is executed!
}
In usefile
my login function is present which is exported. 在
usefile
中,存在我的登录功能,该功能已导出。
I am using passport here, whose functionality is present in separate file here it is used only for authentication. 我在这里使用护照,其功能在单独的文件中提供,仅用于身份验证。
When I ran http://localhost:8080/api/usefile/--- > for get
method, it is displaying 404. same for post
method. 当我为
get
方法运行http:// localhost:8080 / api / usefile / --- >时,它显示404。与post
方法相同。
The console is printing line 1 and line 2(have mentioned in the comments) and the flow is line1, line2. 控制台正在打印第1行和第2行(在注释中已提到),流程是第1行,第2行。
Can anyone help me to find what mistake I have made here? 谁能帮我找到我在这里犯的错误?
You've created two Router instances player
and finalRun
. 您已经创建了两个Router实例
player
和finalRun
。 There are two main issues: 有两个主要问题:
player.use('/usefile',player)
should be app.use('/usefile',player)
. player.use('/usefile',player)
应该是app.use('/usefile',player)
。 express.Router().use
is used to add a middleware for all routes registered to the router (in this case player
). express.Router().use
用于为注册到路由器(在本例中为player
)的所有路由添加中间件。 For example, if you wanted to use the Auth
middleware from Passport for every player
route, you could declare it as player.use(Auth)
. player
路线使用Passport的Auth
中间件,则可以将其声明为player.use(Auth)
。 finalRun
router. finalRun
路由器声明任何路由处理。 So in this case, your route handlers registered with player
will handle host/usefile
and finalRun
will handle any host/api
. player
注册的路由处理程序将处理host/usefile
而finalRun
将处理任何host/api
。 If you are wanting the handlers registered with player
to handle /api/usefile
, using a single router instance would be far simpler. 如果您希望在
player
上注册的处理程序处理/api/usefile
,则使用单个路由器实例会简单得多。
Register the /api/usefile
path with the player
router like: 向
player
路由器注册/api/usefile
路径,例如:
app.use('/api/usefile', player);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.