search

Home  >  Q&A  >  body text

node.js - koa2插入数据成功在给前端返回状态的时候Can't remove headers after they are sent

router/oneBuy.js代码:

var controller = require('../controller/oneBuy');
module.exports = function(app){
    //首页
    app.post('/createOneBuyActive', controller.createOneBuyActive);
};

controller/oneBuy.js代码:

var OneBuyModel = require('../model/OneBuy');

module.exports = {
  async createOneBuyActive () {
    let self = this

    let params = self.request.body;
    let onebuy = {};
    onebuy.id = params.id;
    onebuy.name = params.name;
    onebuy.des = params.des;
    onebuy.createTime = new Date().getTime() + '';
    // 校验参数
    try {
      if (!onebuy.name.length) {
        self.status = 401
        self.body = {retCode: 401, retMsg: '请填写活动名称'}
      }
      if (!onebuy.des.length) {
        self.status = 401
        self.body = {retCode: 401, retMsg: '请填写活动描述'}
      }
      let data = await OneBuyModel.create(onebuy)
      console.log(data)
      if (data.result.ok === 1) {
        self.status = 200
        self.body = {retCode: 200, retMsg: '新增活动成功!'}
      } else {
        self.status = 400
        self.body = {retCode: 400, retMsg: '新增活动失败!'}
      }
    } catch (e) {
      self.status = 500
      self.body = {retCode: 500, retMsg: '服务器异常', error: e}
      // throw new Error(e);
    }
  }
}

报错:

(node:8516) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error:
Can't remove headers after they are sent
(node:8516) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise
rejections that are not handled will terminate the Node.js process with a non-zero exit code.
 
伊谢尔伦伊谢尔伦2866 days ago771

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-04-17 16:32:22

    You should return after assigning a value to .body, otherwise the subsequent code will still be executed, which leads to Can't remove headers after they are sent

    reply
    0
  • Cancelreply