如何确保ExpressJS .route()仅调用一条路由

时间:2019-11-14 15:13:19

标签: node.js express routes

如果我是在React路由器的前端中编写此代码,则将使用一条语句来确保仅调用 一条路由 。但是,这是针对后端的,它是用计划Node.js编写的。

我的目标是让/forms返回所有表单,而/forms/:requestor仅针对特定请求者返回那些表单,即

localhost/forms -> getFormsRoute()

localhost/forms/:requestor -> getFormsForRequestorRoute()

我有一个连接到/forms主文件中的App.js网址的路由器:

// essential parts of App.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const {FormRouter} = require('./routers/FormRouter');

const app = express();
app.use('/forms', FormRouter);

FormRouter.js中代码的简化版本(使用数组而不是数据库查询)如下:

// essential parts of FormRouter.js
const express = require('express');
const {forms} = require('../scaffolding/forms'); // some dummy data in an array ...

const FormRouter = express.Router();

const getFormsForRequestorRoute = (req, res, next) => {
  const { requestor } = req.params;
  console.log(`getFormsForRequestorRoute for ${requestor}`);
  const formsForRequestor = form.filter(function (form) {
    return form.requestor === requestor;
  });
  console.log(formsForRequestor);
  res.json({ rows: formsForRequestor });
};

const getFormsRoute = (req, res, next) => {
  console.log('getFormsRoute');
  res.json({ rows: forms });
};

FormRouter.route('/:requestor')
  .get(getFormsForRequestorRoute);

FormRouter.route('/')
  .get(getFormsRoute);

exports.FormRouter = FormRouter;

当我对/users/smith进行ping操作时,控制台会告诉我自己是自己击中getFormsRoute的。

很明显,这不是我所期望的。令我感到困惑的是,它没有击中getFormsForRequestorRoute,然后再击中getFormsRoute

我缺乏什么了解?我应该怎么做?

2 个答案:

答案 0 :(得分:1)

按以下步骤更改您的路线,这几乎是一种标准:

FormRouter.route('/forms/:requestor')
  .get(getFormsForRequestorRoute);

FormRouter.route('/forms')
  .get(getFormsRoute);
在OP提出进一步的问题后,

更新

这是我注册路线的方式。

app.js

require('./routes/users')(app); // app is express instance

users.js

module.exports = (app) => {
   ....

   app.route('/users')
      .get(getUsers)
      .post(createUser);

   app.route(”/users/:id")
      .get(getUser);

}

答案 1 :(得分:0)

您需要调用next(),否则express将与您声明的第一个路径:/ requestor 相匹配。如果将响应发送回去,则req / res周期结束,并且第二条路由未调用。如果要匹配多条路线,请继续拨打下一个电话。这样做

const express = require('express');
    const {forms} = require('../scaffolding/forms'); // some dummy data 

const FormRouter = express.Router();

const getFormsForRequestorRoute = (req, res, next) => {
  const { requestor } = req.params.requestor;
  console.log(`getFormsForRequestorRoute for ${requestor}`);
  const formsForRequestor = form.filter(function (form) {
    return form.requestor === requestor;
  });
  console.log(formsForRequestor);
  res.json({ rows: formsForRequestor });
};

const getFormsRoute = (req, res, next) => {
  console.log('getFormsRoute');
  res.json({ rows: forms }); 
};

FormRouter.get('/:requestor',getFormsForRequestorRoute);




FormRouter.get('/', getFormsRoute);

exports.FormRouter = FormRouter;