简体   繁体   English

用express.router找不到路线404

[英]Route 404 not found with express.router

I am very new to express and node in general, i have two route handlers with the same path but different method.. I am using express.router() and i was advised to chain the route handlers like this but i get 404 Not found for GET /status but the routes works if i remove my middleware .all(verifytoken) 我一般来说都是Express和Node的新手,我有两个具有相同路径但方法不同的路由处理程序。.我使用express.router() ,建议我像这样链接路由处理程序,但我得到404找不到为GET /状态,但如果我删除中间件.all(verifytoken)则路由有效

statusRouter.route('/status')
  .all(verifyToken)
  .get(status.get)
  .post(status.new);

/statusController / statusController

 get: 
        (req, res) => {
          Post.find({}, (err, posts) => {
              if(err) throw err;

              if(posts){
                  console.log(posts)
                  res.json({message: 'ok'})
              } 
          })
        },
   new: (req, res) => {
       // i omitted the code for simplicity
   }

/middlewares /中间件

    const verifyToken = (req, res, next) => {
   const token = req.headers.authorization.slice(7 - req.headers.authorization.length);
        jwt.verify(token, process.env.KEY1, function(err, decoded) {
            if(err) {
                res.status(401).json({
                    message: "You're session has expired, please login again.",
                    type: 'error',
                    code: 401
                })
            }

            if(decoded){
                next();
            } 
        })
    }

You need to put it in your express app because it is only a router and has not been integrated to your express application, That's why it is returning 404 because it still cannot find your router. 您需要将其放在快速应用程序中,因为它只是一个路由器,尚未集成到快速应用程序中。这就是为什么它返回404的原因,因为它仍然找不到您的路由器。

const express = require('express')
const router = express.Router();
const app = express();

app.use(yourRouter);

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

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