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

/**
* 配置自動化路由和靜態資源目錄,支持絕對和相對路徑,推薦使用 __dirname 拼接
* 目錄能夠是多個,若是出現相同的,先配置的優先級高
*/
autoRouter(__dirname + "/router", app);
app.use(koaStatic("E:/project/GitH5"));koa

相關文章
相關標籤/搜索