Node. js uses Koa to build a basic project, node. jskoa

Source: Internet
Author: User

Node. js uses Koa to build a basic project, node. jskoa

Koa is an ultra-lightweight Server framework built by Express's original team.

Compared with Express, apart from having a higher degree of freedom, you can introduce Middleware on your own. More importantly, ES6 + async is used to avoid callback hell.

But also because of code upgrades, Koa2 requires a node. js environment above v7.60

1. Create a project

Manually create a project directory and quickly generate a package. json File

npm init -y
Install koa // The current version 2.4.1
npm install koa -S
Then create an app. js
// app.jsconst Koa = require('koa');const app = new Koa();app.use(async ctx => { ctx.body = 'Wise Wrong';});app.listen(3000);
Add the startup command in package. json.

This is the most basic koa application.

Run npm start and access http: // localhost: 3000/in the browser to view the effect.

If you think it is too cumbersome to manually create a project, you can use the scaffold koa-generato to generate a project.

npm install koa-generator -g
koa2 project_name
Then install the dependency in npm install under the project, and npm start starts the project.

If you are new to koa, we recommend that you read this blog and then use the scaffolding tool to better understand the role of each dependent package.

Ii. Configure routes

In app. js, there is a ctx, which is a Context object provided by Koa and encapsulates request and response.

Each HTTP Request creates a Context object.

We can use Context. request. path to obtain the path of the user request, and then send the content to the user through Context. response. body.

The default return type of Koa is text/plain. to return an html file (or a module File), you need to modify Context. response. type.

In addition, Context. response can be abbreviated. For example, Context. response. type can be abbreviated to Context. type, and Context. response. body can be abbreviated to Context. type.

Create a directory named views to store html files under the project, create an index.html file under the directory, and modify app. js.

// App. js // native route const Koa = require ('koa'); const fs = require ('fs'); const app = new koa (); app. use (async (ctx, next) =>{ if (ctx. request. path = '/Index') {ctx. type = 'text/html '; ctx. body = fs. createReadStream ('. /views/index.html ');} else {await next () ;}}); app. listen (0, 3000 );
Then access http: // localhost: 3000/index in the browser to view the index.html page, and access other addresses is not found.

In this way, url Processing is very clumsy, so we need to introduce the routing middleware koa-router.

npm install koa-router -S
Note that when importing koa-router, you must add a bracket at the end:
const router = require('koa-router')();
Equivalent:
const koaRouter = require('koa-router');const router = koaRouter();
Create a routes directory to store route files and create index. js under the Directory

// routes/index.jsconst fs = require('fs');const router = require('koa-router')()router.get('/index', async (ctx, next) => { ctx.type = 'text/html'; ctx.body = fs.createReadStream('./views/index.html');});module.exports = router
You can also use the prefix method to add a baseUrl for all interfaces in the file.

// Router. prefix ('/about ')

Modify app. js

// app.jsconst Koa = require('koa');const app = new Koa();const index = require('./routes/index')app.use(index.routes(), index.allowedMethods())app.listen(3000);
The allowedMethods method above is used to verify the request method. If a post request is used to access the get interface, a failure is returned directly.

In addition, you can add a variable to the url and access it through Context. params. name.

router.get('/about/:name', async (ctx, next) => { ctx.body = `I am ${ctx.params.name}!`;});
Iii. Static Resources

In index.html above, if you need to introduce css and other static resources, you need to use koa-static

npm install koa-static -S
Create a public directory to store static Resources

Then add the following code in app. js:

Const static = require ('koa-static '); // set the public directory to the static Resource Directory const main = static (_ dirname +'/public '); app. use (main );
In fact, these three lines of code can be optimized.
app.use(require('koa-static')(__dirname + '/public'));
Then you can introduce the corresponding file in index.html.

 

Iv. template engine

The preceding route uses the fs module to directly read html files.

We recommend using the koa-views middleware to render pages during development.

npm install koa-views -S
Set the views directory as the template directory in app. js.
const views = require('koa-views')app.use(views(__dirname + '/views'));
Then, you can use the render method in the routing file.
// routes/index.jsconst router = require('koa-router')()router.get('/index', async (ctx, next) => { await ctx.render('index');});module.exports = router
The preceding method directly renders html files. To introduce the template engine, you can add the extension field to set the template type.
App. use (views (_ dirname + '/view', {extension: 'pug' // take pug template as an example }))
V. Conclusion

If Express is regarded as webstorm, Koa is sublime.

When Express became popular, its redundant dependencies were criticized by many developers.

Therefore, the Express team only has the most basic skeleton left to allow developers to assemble Express themselves. This is Koa.

As mentioned in this article, it is too cumbersome to start from scratch. You can use scaffolding koa-generato for rapid development.

However, I recommend that you build a scaffold suitable for your project after you are familiar with Koa.

Otherwise, why not use Express directly?

I think this is why the generato tool is not mentioned in the official Koa documentation.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.