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!