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:
1 2 3 4 5 6 7 8 9 | const Koa = require("koa"); const app = new Koa(); app.use(async ctx => { ctx.body = "Hello world"; }); app.listen(3000); |
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:
1 2 3 4 | >> yarn nodemon index.js #yarn #hoặc >> nodemon index.js #npm |
And open to http://localhost:3000 , the output will be as follows:
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:
1 2 3 4 5 6 7 8 9 | app.use(async (ctx, next) => { ctx.body = "Hello world"; await next(); }); app.use(async (ctx) => { ctx.body = "Hello world 2"; }) |
Result:
1 2 3 4 5 6 7 8 | app.use(async (ctx, next) => { ctx.body = "Hello world"; }); app.use(async (ctx) => { ctx.body = "Hello world 2"; }) |
Result: