我正在使用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 回答
如果您使用的是
async
函数,那么您应该按照async
/`await?模式,而不是使用回调 . 所以你应该改写你的电话,如:我遇到了同样的问题,因为我在前面的代码中使用了链式
sendStatus
函数 .删除额外
sendStatus
解决了我的问题 .