Hello world with Koajs

Tram Ho

In all programming languages, most of us start with a simple Hello world program. In today’s article, we will write a hello world program together and review the knowledge in the code.

Hello world with Koajs

First, create an index.js file in the KoaShop folder:

photo.png In index.js:

In the above code:

  • const Koa = require("koa"); : import koa library.
  • const app = new Koa(); : initialize app.
  • app.use(async ctx => { return ctx.body = "Hello world"; }); : attach a middleware (the function will be called when there is an incoming request) to the application.
  • app.listen(3000); : launch the app on port 3000 ( http://localhost:3000 ).
    To be more intuitive, open the terminal to run the app:

And open to http://localhost:3000 , the output will be as follows: photo.png

More details about middleware in Koajs

In the above program, we have a simple middleware that is an async function that takes a ctx parameter (equivalent to this, in newer versions of koajs most use arrow function). Ctx is both a request and a response and it also contains a lot of useful methods for writing web apps and APIs. Learn more . In addition to ctx, most middleware in a Koa app has an additional parameter called next, which is used to continue to the next middleware, for example the code below:

Result: photo.png But if now we delete the line await next(); So what do people think?

Result:

Share the news now

Source : Viblo