node 搭建本地服务器

本文介绍了一个基于Koa.js框架的实战应用案例,包括了服务器搭建、中间件使用、自动化路由配置及静态资源托管等内容。文章详细展示了如何通过Koa.js进行HTTP服务的快速构建,并实现了日志记录、跨域访问等功能。

/**
* 代理服务器 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"));

 

转载于:https://www.cnblogs.com/xianxianxxx/p/9254932.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值