Home > Web Front-end > JS Tutorial > Share an example tutorial on using the koa2 framework in nodejs

Share an example tutorial on using the koa2 framework in nodejs

零下一度
Release: 2017-05-19 09:31:36
Original
2011 people have browsed it

This article mainly introduces examples of using the koa2 framework under nodejs6. The editor thinks it is quite good. Now I will share it with you and give it a reference. Let’s follow the editor and take a look.

koa2 uses ES7 syntax, such as async and await, so it needs to run after node7.6; but before node7.6, babel can also be used, so koa2 can run.

First install babel in the project, and several babel modules:

npm install babel babel-register babel-preset-env --save
Copy after login

Then introduce the 'babel-register' module in the entry file

require('babel-register');
Copy after login

Then introduce it Business code:

require('./server.js');
Copy after login

In the configuration .babelrc file:

{
 "presets": [
  ["env", {
   "targets": {
    "node": true
   }
  }]
 ]
}
Copy after login

Example:

app.js:

require('babel-register');

require('./servers/devserver');
Copy after login

devserver.js:

var koa = require('koa');
var app = new koa();
const request = require('request');


let port = process.env.PORT || 8080;
console.log("set port:" + process.env.PORT + "; ip:" + process.env.IP);
app.use(async (ctx) => {
 console.log(ctx.url);
 if (ctx.url.indexOf('/aaa') > -1) {
  
  ctx.response.set('content-type', 'text/javascript');
  ctx.body = request.get('http://127.0.0.1/aa.bundle.js', function(err, response, body) {
   console.log(body);
  });
 }
});
app.listen(port);
Copy after login

【Related recommendations】

1. Free js online video tutorial

2. JavaScript Chinese Reference Manual

3. php.cn Dugu Jiujian (3) - JavaScript video tutorial

The above is the detailed content of Share an example tutorial on using the koa2 framework in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template