nodejs6下使用koa2框架实例
koa2里面使用ES7的语法,如async、await所以需要运行在node7.6之后;但在node7.6之前也可以利用babel是的koa2可以运行。
首先项目中安装babel,和babel的几个模块:
npm install babel babel-register babel-preset-env --save
然后在入口文件中引入‘babel-register'模块
require('babel-register');
而后引入业务代码:
require('./server.js');
在配置.babelrc文件:
{ "presets": [ ["env", { "targets": { "node": true } }] ] }
示例:
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);
相关推荐
boneix 2020-10-21
MrQuinn 2020-08-16
starzhangkiss 2020-04-19
LorenLiu 2020-03-28
Qimingweikun 2020-03-05
发条戏子 2020-02-01
jackyhungvip 2020-01-19
Qimingweikun 2019-12-09
Anything0 2019-11-17
lert0 2019-11-04
88530198 2019-11-03
sqliang 2019-11-03
苹果咏 2019-07-23
bobbaobao 2018-11-13
lert0 2019-07-01
fanix 2019-07-01
liwenbocsu 2019-07-01