Chain Express方法

时间:2018-01-08 01:22:00

标签: javascript node.js express

我有一台带有CRUD方法的Express服务器

我希望在触发postputdelete时,get方法也会在之后运行,以便在我的前端更新视图

这是我的routes.js代码

// ROUTES FOR OUR API
// =============================================================================
var express = require("express"); // call express
var NouvProj = require("../app/models/nouvProj");
var mongoose = require("mongoose");

var router = express.Router(); // get an instance of the express Router

router.use(function(req, res, next) {
  next(); // make sure we go to the next routes and don't stop here
});

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router
  .route("/projets")

  // create a nouvProj (accessed at POST http://localhost:8080/api/nouvProjs)
  .post(function(req, res, next) {
    var nouvProj = new NouvProj();
    // create a new instance of the nouvProj model

    nouvProj.nomProj = req.body.nomProj;
    nouvProj.leadProj = req.body.leadProj;
    nouvProj.descProj = req.body.descProj;
    nouvProj.BesProj = req.body.BesProj;
    nouvProj.pers = req.body.pers;
    nouvProj.backlog.fonctionnalite = req.body.Fonctionnalite;
    nouvProj.backlog.userStory = req.body.UserStory;
    // save the nouvProj and check for errors
    nouvProj.save(function(err) {
      if (err) {
        res.send(err);
        console.log("err");
      }
      res.json({
        message: "nouvProj created!"
      });
    });
    next();
  })

  .get(function(req, res) {
    NouvProj.find(function(err, nouvProj) {
      if (err) res.send(err);
      else {
        res.json(nouvProj);
        console.log(req.io);
      }
    });
  });
router
  .route("/nouvProjs/:nouvProj_id")

  // get the nouvProj with that id (accessed at GET http://localhost:8080/api/nouvProjs/:nouvProj_id)
  .get(function(req, res) {
    //console.log(req.params.nouvProj_id);
    NouvProj.findById(req.params.nouvProj_id, function(err, nouvProj) {
      if (err) {
        res.send(err);
      } else {
        //console.log(nouvProj);

        res.json(nouvProj);
      }
    });
  })
  .put(function(req, res) {
    NouvProj.findById(req.params.nouvProj_id, function(err, nouvProj) {
      if (err) res.send(err);
      nouvProj.nomProj = req.body.nomProj;
      nouvProj.leadProj = req.body.leadProj;
      nouvProj.descProj = req.body.descProj;
      nouvProj.BesProj = req.body.BesProj;
      nouvProj.pers = [{ name: req.body.name, poste: req.body.poste }];
      nouvProj.backlog.fonctionnalite = req.body.Fonctionnalite;
      nouvProj.backlog.userStory = req.body.UserStory;

      nouvProj.save(function(err) {
        if (err) res.send(err);

        res.json({
          message: "nouvProj updated!"
        });
      });
    });
  })

  .delete(function(req, res) {
    NouvProj.remove(
      {
        _id: req.params.nouvProj_id
      },
      function(err, nouvProj) {
        if (err) res.send(err);

        res.json({
          message: "Successfully deleted"
        });
      }
    );
  });
module.exports = router;

没有next()中间件我的应用程序正在发布并获取数据。但是当我添加next()时:

Error: Can't set headers after they are sent.

从这部分代码开始:

  res.json({
    message: "nouvProj created!"
  });
});
next();

如何解决这个问题,并且能够在每次添加数据时更新get方法?

2 个答案:

答案 0 :(得分:1)

在调用res.send()之前,您无法在中间件函数中调用res.json() res.render() next()等。一旦调用响应,Express就会停止执行链。

如果你想"链"响应,您可以使用像请求(https://www.npmjs.com/package/request)这样的库来发出多个HTTP调用。这是默认示例之一:

request
  .get('http://example.com/img.png')
  .on('response', function(response) {
    console.log(response.statusCode) // 200
    console.log(response.headers['content-type']) // 'image/png'
  })
  .pipe(request.put('http://example.com/img.png'))

答案 1 :(得分:1)

您无法向一个请求发送多个回复,而不是HTTP的工作方式,以及这就是您收到错误的原因。

大多数人都会在这样的API上使用两种方法。要么只返回带有POST响应的对象(例如res.json({ message: 'Success!', project: nouvProj });),要么让客户端在获得成功响应后进行GET查询。