首页 文章

Koa js:呃:可以't set headers after they'重新发送 . MongoDB的

提问于
浏览
0

我正在使用Koa 2的异步功能 .

我收到以下错误 .

events.js:163 1:56 PM throw er; //未处理'错误'事件1:56 PM ^ 1:56 PM 1:56 PM错误:发送后无法设置 Headers . 下午1:56在ServerResponse.setHeader(_http_outgoing.js:371:11)1:56 PM at Object.set(/app/node_modules/koa/lib/response.js:440:16)1:56 PM at Object . 在Object.proto重定向(/app/node_modules/koa/lib/response.js:261:10)1:56 PM . (匿名函数)[作为重定向](/app/node_modules/delegates/index.js:40: 31)1:56 PM在model.Query跳转到url.findOne(/app/server.js:126:9)1:56 PM . (/app/node_modules/mongoose/lib/model.js:3737:16)下午1:56 at /app/node_modules/kareem/index.js:277:21 1:56 PM / app / node_modules / kareem / index .js:131:16 1:56 PM atcombinTickCallback(internal / process / next_tick.js:73:7)1:56 PM at process._tickCallback(internal / process / next_tick.js:104:9)1:56 PM 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 .

2 回答

  • 0

    如果您使用的是 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;
      }
    }
    
  • 1

    我遇到了同样的问题,因为我在前面的代码中使用了链式 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);
            }
    });
    

相关问题