You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
2.1 KiB
63 lines
2.1 KiB
2 years ago
|
const Koa = require('koa'),
|
||
|
Router = require('koa-router'),
|
||
|
art = require('koa-art-template'),
|
||
|
path = require('path'),
|
||
|
static = require('koa-static'),
|
||
|
bodyParser = require('koa-bodyparser');
|
||
|
const routers = require('./routers/routers')
|
||
|
|
||
|
|
||
|
const app = new Koa();// 创建koa应用
|
||
|
const router = new Router(); // 创建路由,支持传递参数
|
||
|
art(app, {
|
||
|
root: path.join(__dirname, 'templates'),
|
||
|
extname: '.html',
|
||
|
debug: process.env.NODE_ENV !== 'production',
|
||
|
cache:false,
|
||
|
minimize: true
|
||
|
});// 将art模板导入到koa项目中
|
||
|
app.use(static(`${__dirname}/static`));// 设置静态文件读取目录,可以设置多个
|
||
|
app.use(bodyParser());// 设置使用bodyParser接受POST数据
|
||
|
app.use(async (ctx,next)=>{
|
||
|
await next();
|
||
|
// console.log(ctx.status);
|
||
|
if(parseInt(ctx.status)===404){
|
||
|
ctx.body=404;
|
||
|
}
|
||
|
// ctx.response.redirect('/about');//重定向
|
||
|
});// 定制404页面
|
||
|
|
||
|
|
||
|
router.use('/',routers.routes());
|
||
|
|
||
|
|
||
|
/*
|
||
|
|
||
|
router.get('/', async (ctx) => {
|
||
|
await ctx.render('input');
|
||
|
console.log(ctx.request)
|
||
|
// console.log(ctx.request.url);
|
||
|
// // console.log(ctx.request);
|
||
|
// console.log(ctx.request.query.name);// 获取get参数,获取不到是undefined
|
||
|
// console.log(ctx.request.querystring);// 将get参数转化为字符串格式
|
||
|
// console.log(ctx.params);// 获取动态路由
|
||
|
})
|
||
|
router.post("/123", async (ctx)=>{
|
||
|
ctx.body=ctx.request.body;
|
||
|
console.log(ctx.request.body)
|
||
|
})
|
||
|
*/
|
||
|
|
||
|
|
||
|
// 调用router.routes()来组装匹配好的路由,返回一个合并好的中间件
|
||
|
// 调用router.allowedMethods()获得一个中间件,当发送了不符合的请求时,会返回 `405 Method Not Allowed` 或 `501 Not Implemented`
|
||
|
app.use(router.routes());
|
||
|
app.use(router.allowedMethods({
|
||
|
// throw: true, // 抛出错误,代替设置响应头状态
|
||
|
// notImplemented: () => '不支持当前请求所需要的功能',
|
||
|
// methodNotAllowed: () => '不支持的请求方式'
|
||
|
}));
|
||
|
// 这俩要放在最后
|
||
|
app.listen(9999,()=>{
|
||
|
console.log("服务器已经启动:http://localhost:80")
|
||
|
})
|