简体   繁体   English

如何正确设置路线?

[英]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实例playerfinalRun There are two main issues: 有两个主要问题:

  1. This line 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)
  2. You are not declaring any route handling for the 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/usefilefinalRun将处理任何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);

Docs for app.use 适用于应用app.use文档

Docs for router.use 用于router.use文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM