Search code examples
node.jspostkoa

Why my ctx.request.files is undefined, while ctx.request.body is ok?


I'm trying to parse data from my simple form using koa-body, but in post request handling I only can access ctx.request.body , but not ctx.request.files. I was trying several options t solve this, but it's not working out, ctx.request.files is empty in anyways. Wrote code according this example:koa-body/examples/multipart.js . There is code:

reg.js

const router = require('koa-router')();
const bodyParser = require('koa-body')({multipart:true});

router.post('/reg', bodyParser,  async (ctx) => {
        console.dir(ctx.request);
});

module.exports = router;

reg.pug

     form(method='POST' action='/reg')
                    label Логин
                    input(type="text" id="login" name="login")
                    label Почта
                    input(type="text" name="mail")
                    label Пароль
                    input(type="password" name="password")
                    label Специализация
                    input(type="text" name="specialism")
                    label Пол
                    select(name="sex")
                        option(value="male") Мужрской
                        option(value="female") Женский
                    label Фото
                    input(type="file" name="image")
                    button(type="submit" value="Sign up") Sign Up

app.js

const Koa = require('koa');
const Pug = require('koa-pug');
const serve = require('koa-static');
const path = require('path');
const logger = require('koa-morgan');

const mongoDB = require('./config/database');
const homeRoute = require('./routes/home');
const regRoute = require('./routes/reg');

const app = new Koa();

// Connection to Mongoose
mongoDB.connect();

app.use(logger('dev'));

// Error-middleware handler
app.use(async(ctx, next) => {
    try {
        await next();
        const status = ctx.status || 404;
        if (status === 404) {
            ctx.throw(404)
        }
    } catch (err) {
        ctx.status = err.status || 500;
        pug.locals.status = ctx.status;
        if (ctx.status === 404) {
            //Your 404.jade
            await ctx.render('404error', pug.locals)
        } else {
            //other_error jade
            await ctx.render('index', pug.locals)
        }
    }
});

app.use(serve(`${__dirname}/public`));

const pug = new Pug({
    viewPath: path.resolve(__dirname, './views'),
    locals: { },
    app: app
});

app.use(homeRoute.routes());
app.use(regRoute.routes());

app.listen(3000, function(){
    console.log('Server running on https://localhost:3000')

That's what ctx.request.body contains:

 body: {
    login: 'check',
    mail: '123',
    password: '123',
    specialism: 'check',
    sex: 'male',
    image: 'SnWyoGZWgDA.jpg'
  }

Solution

  • I was having the same issue in a new project. This is an issue in the new version of koa-body. I changed koa-body version from "^4.1.1" to "^2.5.0". Now it is working fine.

    To update use command:

    npm remove koa-body
    

    The install older version:

    npm install koa-body@2.5.0
    

    Now it will work fine.