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.
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
Most helpful comment
I solved it.
This is wrong:
and this is right:
this is right, too: