Koa: AssertionError [ERR_ASSERTION]: headers have already been sent

Created on 9 Aug 2017  路  3Comments  路  Source: koajs/koa

This is my code.

import Koa from 'koa';
import Router from 'koa-router';
import multer from 'koa-multer';

const router = new Router();
const app = new Koa();
const uploadMulter = multer({ dest: 'public/upload/' });

router.post('/upload', uploadMulter.array('files'), async (ctx, next) => {
    ctx.status = 200;
    ctx.body = { answer: 'ok' };
    return next();
});

When I upload files, it upload to the dir successfully, but when I set ctx.status or ctx.body , the log prints this, and return to client 404 (Not Found)

(node:7299) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): AssertionError [ERR_ASSERTION]: headers have already been sent
(node:7299) [DEP0018] 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.

Most helpful comment

I solved it.
This is wrong:

app.use(async (ctx, next) => {
    await VisitDao.createVisit({
        method: ctx.request.method,
        href: ctx.request.href,
        ip: ctx.request.ip,
        status: ctx.status
    });
   next();
});

and this is right:

app.use(async (ctx, next) => {
    await VisitDao.createVisit({
        method: ctx.request.method,
        href: ctx.request.href,
        ip: ctx.request.ip,
        status: ctx.status
    });
    await next();
});

this is right, too:

app.use(async (ctx, next) => {
    await VisitDao.createVisit({
        method: ctx.request.method,
        href: ctx.request.href,
        ip: ctx.request.ip,
        status: ctx.status
    });
    return next();
});

All 3 comments

I saw a similar issue #716, but where am I wrong?

I solved it.
This is wrong:

app.use(async (ctx, next) => {
    await VisitDao.createVisit({
        method: ctx.request.method,
        href: ctx.request.href,
        ip: ctx.request.ip,
        status: ctx.status
    });
   next();
});

and this is right:

app.use(async (ctx, next) => {
    await VisitDao.createVisit({
        method: ctx.request.method,
        href: ctx.request.href,
        ip: ctx.request.ip,
        status: ctx.status
    });
    await next();
});

this is right, too:

app.use(async (ctx, next) => {
    await VisitDao.createVisit({
        method: ctx.request.method,
        href: ctx.request.href,
        ip: ctx.request.ip,
        status: ctx.status
    });
    return next();
});

What a useful error... thank you @ koajs

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tracker1 picture tracker1  路  3Comments

SteveCruise picture SteveCruise  路  5Comments

sibelius picture sibelius  路  3Comments

edahlseng picture edahlseng  路  3Comments

koalex picture koalex  路  3Comments