node 搭建本地服务器

/**
* 代理服务器 natapp -authtoken f1bdaa0535788971
* 热部署指令 supervisor index
*/
const Koa = require('koa')
const koaStatic = require('koa-static')
const bodyParser = require('koa-bodyparser')
const autoRouter = require('./util/koa-automate-router')
const log4jsUtil = require('./util/log4js-util')

/**
* 实例化 KOA 服务器,载入三方中间件到服务器实例
* POST 参数解析功能 ctx.request.body.key 获取
*/
const app = new Koa();
app.use(bodyParser());
app.listen(80, function () { console.log("服务器启动成功") });

/**
* 将项目根路径载入到 KOA 实例中,方便其它目录下访问跟路径 ctx.rootPath = __dirname
* 允许跨域访问 ctx.res.setHeader('Access-Control-Allow-Origin', '*')
* 客户端访问IP ctx.req.headers['x-forwarded-for'] || ctx.req.connection.remoteAddress
*/
const notesLog = log4jsUtil.notesLog;
const errorLog = log4jsUtil.errorLog;
app.use(async (ctx, next) => {
try {
ctx.rootPath = __dirname;
ctx.res.setHeader('Access-Control-Allow-Origin', '*');
let clientIp = ctx.req.headers['x-forwarded-for'] || ctx.req.connection.remoteAddress;
let notes = '[' + clientIp + ']'
notes += ' [' + ctx.request.method + ']';
notes += ' [' + ctx.request.url.split("?")[0] + ']';
notesLog.info(notes);
await next();
} catch (err) {
errorLog.error(err.stack);
ctx.body = { code: 0, info: err.stack };
}
});

/**
* 配置自动化路由和静态资源目录,支持绝对和相对路径,推荐使用 __dirname 拼接
* 目录可以是多个,如果出现相同的,先配置的优先级高
*/
autoRouter(__dirname + "/router", app);
app.use(koaStatic("E:/project/GitH5"));

 

posted @ 2018-07-02 17:38  咚咚酱  阅读(197)  评论(0编辑  收藏  举报