Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using express middleware in koa

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?

like image 658
urish Avatar asked Aug 19 '14 13:08

urish


People also ask

Can you use Express middleware with KOA?

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.

Is KOA better than Express?

The key difference between Koa and Express is how they handle middleware. Express includes routing and templates in the application framework. Koa, on the other hand, requires modules for these features, therefore making it more modular or customizable.

How do you write KOA middleware?

The way I write middleware is pretty similar with @Sebastian: const Koa = require('koa'); const app = new Koa(); const render = async(ctx, next) { // wait for some async action to finish await new Promise((resolve) => { setTimeout(resolve, 5000) }); // then, send response ctx. type = 'text/html'; ctx.

What is middleware KOA?

Koa Application The application object is Koa's interface with node's http server and handles the registration of middleware, dispatching to the middleware from http, default error handling, as well as configuration of the context, request and response objects.


2 Answers

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);
like image 191
Tomas Holas Avatar answered Oct 01 '22 22:10

Tomas Holas


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.

like image 24
marco Avatar answered Oct 01 '22 23:10

marco