Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Koa is being executed twice per request?

Tags:

node.js

koa2

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?

like image 958
Run Avatar asked Oct 16 '25 08:10

Run


1 Answers

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.

like image 177
Sebastian Hildebrandt Avatar answered Oct 18 '25 21:10

Sebastian Hildebrandt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!