【问题标题】:Koa js : Err: Can't set headers after they're sent. mongoDBKoa js:错误:发送后无法设置标头。 MongoDB数据库
【发布时间】:2017-10-05 09:09:53
【问题描述】:

我正在使用 Koa 2 的异步函数。

我收到以下错误。

events.js:163 下午 1 点 56 分 投掷者; // 未处理的“错误”事件 下午 1 点 56 分 ^ 下午 1 点 56 分 下午 1 点 56 分 错误:发送后无法设置标头。 下午 1 点 56 分 在 ServerResponse.setHeader (_http_outgoing.js:371:11) 下午 1 点 56 分 在 Object.set (/app/node_modules/koa/lib/response.js:440:16) 下午 1 点 56 分 在 Object.redirect (/app/node_modules/koa/lib/response.js:261:10) 下午 1 点 56 分 在 Object.proto.(匿名函数) [作为重定向] (/app/node_modules/delegates/index.js:40:31) 下午 1 点 56 分 跳到 在 url.findOne (/app/server.js:126:9) 下午 1 点 56 分 在模型.查询。 (/app/node_modules/mongoose/lib/model.js:3737:16) 下午 1 点 56 分 在 /app/node_modules/kareem/index.js:277:21 下午 1 点 56 分 在 /app/node_modules/kareem/index.js:131:16 下午 1 点 56 分 在 _combinedTickCallback (内部/进程/next_tick.js:73:7) 下午 1 点 56 分 在 process._tickCallback (internal/process/next_tick.js:104:9) 下午 1 点 56 分 6 分钟前

这是我的代码的一部分。

async function red(ctx) {
  let redurl = "//url here";
  url.findOne({ shortenedLink: redurl }, (err, data) => {
    //find if short url matches long url in db
    if (err) throw err;
    if (data) {
      //if matches then redirect to long url
      ctx.redirect(data.url); //getting the error here
      console.log("matched");
    } else console.error("--"); 
  });
}

我的完整代码可以在here找到。

【问题讨论】:

    标签: node.js mongodb async-await koa mlab


    【解决方案1】:

    如果您使用的是async 函数,那么您应该遵循async/`await?模式而不使用回调。所以你应该重写你的电话:

    async function red(ctx) {
      let redurl = "//url here";
      try {
          data = await url.findOne({ shortenedLink: redurl })
          if (data) {
            ctx.redirect(data.url); //getting the error here
            console.log("matched");
          } else {
            console.error("--"); 
          }
      } catch (err) {
          throw err;
      }
    }
    

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题,因为我在前面的代码中使用了链式 sendStatus 函数。

      Country.count({ name: name }, (error, count) => {
              if (count > 0) {
                  console.log(count);
                  error = name + alreadyExists;
                  res.sendStatus(500).sendStatus(500);
              }
      });
      

      删除多余的sendStatus 解决了我的问题。

      Country.count({ name: name }, (error, count) => {
              if (count > 0) {
                  console.log(count);
                  error = name + alreadyExists;
                  res.sendStatus(500);
              }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-08
        • 2018-06-29
        • 2013-12-22
        相关资源
        最近更新 更多