Using express middleware in koa
Asked Answered
C

3

13

I have existing code which implements an express middleware. How can I use this middleware in a Koa application?

When I try to call app.use(expressMiddleware) in order to use the middleware in my Koa app, Koa complains that a generator function is required:

AssertionError: app.use() requires a generator function

So I guess that some kind of adapter or trick is needed here... ideas?

Cuellar answered 19/8, 2014 at 13:59 Comment(0)
Z
20

Also, you can try koa-connect: https://github.com/vkurchatkin/koa-connect

It looks quite straightforward:

var koa = require('koa');
var c2k = require('koa-connect');
var app = koa();

function middleware (req, res, next) {
  console.log('connect');
  next();
}

app.use(c2k(middleware));

app.use(function * () {
  this.body = 'koa';
});

app.listen(3000);
Zippora answered 8/5, 2015 at 13:17 Comment(1)
Funny thing, koa-connect was created at the very same day when I originally asked this question :)Cuellar
F
5

koa is incompatible with express middleware. (see this blog post for a detailed explaination, especially the part 'Better written middleware').

You could rewrite you middleware for koa. The koa wiki has a special guide for writing middleware.

The req and res that you would receive in an express middleware are not directly available in koa middleware. But you have access to the koa request and the koa response objects via this.request and this.response.

Farlee answered 16/9, 2014 at 0:54 Comment(1)
Thanks Marco, though, I was hoping to find a way to work around this limitation...Cuellar
I
3

I have create koa2-connect on npm for koa2. https://github.com/cyrilluce/koa2-connect

npm i koa2-connect -S
// usage same as koa-connect

Because koa-connect's author haven't publish next version( npm i koa-connect@next didn't work ), and it is not compatible with webpack-dev-middleware and webpack-hot-middleware.

Intimidate answered 11/1, 2017 at 8:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.