如果使用/:var / action,为什么找不到我的路线

时间:2019-04-16 18:05:31

标签: node.js express

我的app.js具有以下内容:

const express = require('express');
const app = express();

const userRoutes = require('./api/routes/users');

// middleware - takes info passed in through the body
app.use(express.urlencoded({extended: false}));
app.use(express.json());

// middleware - adds headers to allow CORS.
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  if(req.method === 'OPTIONS') {
    res.header('Access-Control-Allow-Methods', 'PUT, POST, DELETE, GET');
    res.status(200).json({});
  }
  next();
});

// middleware - filter all requests for users to the userRoutes
app.use('/api/v1/users', userRoutes);

// middleware - catch any requests that aren't caught by previous filters
app.use((req, res, next) => {
  const error = new Error('No route found');
  error.status = 404;
  next(error);
});

// middleware - catch any errors that happen other places in the application (DB, etc.)
app.use((error, req, res, next) => {
  res.status(error.status || 500);
  res.json({
    error: { message: error.message }
  });
});

module.exports = app;

和我的userRoutes看起来像这样:

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

const userController = require('../controllers/userController');
const gtrController = require('../controllers/gtrController');
const DAL = require('../DAL/dal');

router.get('/:userName', (req, res, next) => {
  userController.getUser(req.params.userName, DAL.findOne, gtrController.getUser)
    .then((result) => {
      res.status(200).json(result);
    })
    .catch((error) => {
      console.log(error);
      res.status(500).json({ Error: { message: error }})
    });
});

router.get('/:userName/games', (req, res, next) => {
  userController.getUserStuff(req.params.userName, () => {}, gtrController.getUserStuff)
    .then((result) => {
      res.status(200).json(result);
    })
    .catch((error) => {
      console.log(error);
      res.status(500).json({ Error: { message: error }})
    });
});module.exports = router;

如果我在Postman中检查/和/ username,则得到200,并且一切正确。但是,当我尝试使用/ username / games时,我得到了404。我不确定为什么它没有达到我的userRoutes。我假设这是我的app.use,但找不到任何相关文档。

谢谢。

1 个答案:

答案 0 :(得分:0)

我想出来了。我的router.get('/:userName/games)应该是router.get('/:userName\/games')