Run
Run

Reputation: 57226

Koa is being executed twice per request?

Is there any reason why Koa is being executed twice per request?

const Koa = require('koa')
const app = new Koa()

const index = async(ctx, next) => {
  console.log('Hello world!')
  await next()
  ctx.body = 'Hello world!'
}

app.use(index);

app.listen(3000)

On my terminal, I get:

Hello world!
Hello world!

Any ideas?

Upvotes: 4

Views: 1637

Answers (1)

Sebastian Hildebrandt
Sebastian Hildebrandt

Reputation: 2781

There are two reasons why this could happen:

First is - as already mentioned in the comments that browsers also fire a request for favicon.ico Second: some browsers do a prefentching, so before you even hit the return key, they prefetch the url when entering.

const Koa = require('koa')
const app = new Koa()

const index = async(ctx, next) => {
  console.log('URL --> ' + ctx.request.url); // This logs out the requested route
  console.log('Hello world!')
  await next()
  ctx.body = 'Hello world!'
}

app.use(index);

app.listen(3000)

I added one line to your code so that you can see which routes your browser asks for. This might help identify the reason for your problem.

Upvotes: 7

Related Questions