Home > Web Front-end > JS Tutorial > Tutorial on using koa2 framework in nodejs6

Tutorial on using koa2 framework in nodejs6

Y2J
Release: 2018-05-14 16:43:02
Original
2135 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 'babel- in the entry file register' module

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

Then introduce the 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. Javacript free video tutorial

2. Detailed explanation of examples of jQuery Validate verification of multiple names

3. Detailed examples of easyUI drop-down list click events

4. webpack development environment Cross-domain example tutorial

5. Introduction to the method of JS implementing loop deletion of elements in an array

The above is the detailed content of Tutorial on using koa2 framework in nodejs6. 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