javascript - express 多条删除路由

标签 javascript express sequelize.js

我正在使用带有 sequelize 的 MEAN 堆栈。我有两种情况要从表中删除记录:

1) 使用给定的 id 删除单个记录。

2) 删除满足某些条件的所有记录(共享 projectId 的所有记录)。为此,我正在尝试设置两条路线来处理每种情况。

客户端服务(案例1):

  this.deleteCampaign = function(id) {
    return $http.delete(campaignBaseUrl + id);
  };

客户端服务(案例2):
  this.deleteMultipleCampaigns = function(projectID) {
    return $http.delete(campaignBaseUrl+ 'foo/' + projectID);
  };

服务器端路由:
// I want case 1 to access this route (working)
router.delete('/:id', controller.destroy);
// I want case 2 to access this route (not working)
router.delete('/foo/:projectID', controller.destroyMultiple);

更新
服务器端 Controller :
// Deletes multiple Campaign from the DB
// for a give project ID
export function destroyMultiple(req, res) {
  console.log('req.params:');
  console.log(req.params); // { projectID: '7' }
  Campaign.findAll({
    where: {
      projectId: req.params.projectID
    }
  })
    .then(handleEntityNotFound(res))
    .then(removeEntity(res))
    .catch(handleError(res));
}

// Deletes a single Campaign from the DB
export function destroy(req, res) {
  console.log('destroySingle:');
  Campaign.find({
    where: {
      _id: req.params.id
    }
  })
    .then(handleEntityNotFound(res))
    .then(removeEntity(res))
    .catch(handleError(res));
}

更新 2

服务器端 Controller 续...
function removeEntity(res) {
  return function(entity) {
    if (entity) {
      return entity.destroy()
        .then(() => {
          res.status(204).end();
        });
    }
  };
}

当我从客户端运行 case2 时,出现此错误:DELETE /api/campaigns/foo/7 500{"name":"SequelizeDatabaseError","message":"invalid input syntax for integer: \"foo\"","parent":

最佳答案

express.js 文档说明

The order of middleware loading is important: middleware functions that are loaded first are also executed first.



这意味着在您当前的路由器配置中
// I want case 1 to access this route (working)
router.delete('/:id', controller.destroy);
// I want case 2 to access this route (not working)
router.delete('/foo/:projectID', controller.destroyMultiple);

第一个路由也匹配 url/api/campaigns/foo/7。第二条路由是否更好地匹配 url 并不重要。第一个路由捕获 'foo/7' 或 'foo' 作为参数 :id 。无论哪种方式,该值都不是整数。

我想字段 campaign.projectId 是一个整数,而 boooooom :抛出 Sequelize 错误。

可能的解决方案

把更具体的路线放在第一位。像这样:
router.delete('/foo/:projectID', controller.destroyMultiple);
router.delete('/:id', controller.destroy);

关于javascript - express 多条删除路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38081523/

相关文章:

Javascript TypeError 指出列表未定义

node.js - nodemon 应用程序在尝试请求 mongoose 时崩溃

node.js - 使用历史模式通过 Express.js 服务 VueJS 构建

node.js - Sequelize 模型中的继承

javascript - 在 Twitter Bootstrap 弹出窗口中引用对象

javascript - Web 服务器上的元编程

javascript - 为什么 Sequelize 时间戳没有关闭

node.js - 在sequelize中双重包含,node.js

JavaScript 对象装饰器

javascript - Express - 在中间件函数之间传递数据的更好模式