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

Share an example tutorial on using the koa2 framework in nodejs

零下一度
零下一度Original
2017-05-19 09:31:361911browse

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

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

require('babel-register');

Then introduce it Business code:

require('./server.js');

In the configuration .babelrc file:

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

Example:

app.js:

require('babel-register');

require('./servers/devserver');

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);

【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!

Statement:
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