个人网站做百度云电影链接犯法吗,网页打不开视频,加强文明网站内容建设,网络规划设计师培训最近有个需求需要使用到koa搭建服务器并编写接口对数据库进行增删改查#xff0c;因此写一篇博客记录这段时间的收获。
一、新建koa项目
#xff08;一#xff09;安装koa及其相关依赖
npm i koa
npm i koa-router// 中间件#xff0c;用于匹配路由
npm i koa-bodyparse…最近有个需求需要使用到koa搭建服务器并编写接口对数据库进行增删改查因此写一篇博客记录这段时间的收获。
一、新建koa项目
一安装koa及其相关依赖
npm i koa
npm i koa-router// 中间件用于匹配路由
npm i koa-bodyparser// 中间件用于解析请求body
npm i koa-static// 中间件用于设置静态资源目录
二搭建koa服务器
// app.js
const http require(http);
const Koa require(koa);
const bodyParser require(koa-bodyparser);
const router require(./routes/index);
const static require(koa-static);
const config require(./config);module.exports async () {// 创建koa应用const app new Koa();//设置静态资源目录用于存放前端代码build后的内容app.use(static(public));// 注册中间件app.use(bodyParser());// 路由业务入口app.use(router.routes(), router.allowedMethods());// 启动服务const server http.createServer(app.callback());server.listen(config.serverPort);server.on(error, onServerError);server.on(listening, () {logger.info(服务启动于端口 ${config.serverPort});});
};function onServerError(error) {if (error.syscall ! listen) {throw error;}const bind typeof config.serverPort string ? Pipe ${config.serverPort} : Port ${config.serverPort};// handle specific listen errors with friendly messagesswitch (error.code) {case EACCES:logger.fatal(${bind} 需要更高的权限);process.exit(1);case EADDRINUSE:logger.fatal(${bind} 端口已被使用请检查是否开启了多个服务。);process.exit(1);default:throw error;}
}一般在项目中接口可以分为好多不同的模块的如果把所有的接口请求处理函数都放在上面的 app.js文件就会显得非常庞大且杂乱。所以
1、新增一个routes文件夹专门用来存放路由
// routes/index.js
const createRouter require(koa-router);
const Home require(../controllers/Home);const router createRouter();router.get(/, async (ctx) {ctx.body helloWorld;});router.post(/test, Home.test;module.exports router;2、新增一个controllers文件夹把接口的处理函数统一放在这里
// controllers/index.js
const test async (ctx, next) {ctx.body 测试
}
三启动服务器
直接在app.js的当前文件夹下下node app.js即可启动服务器