Node.js 开发Rest的Api示例项目(二)

举报
清雨小竹 发表于 2022/09/25 00:01:14 2022/09/25
【摘要】 app.js 'use strict'; console.log('Hello world');const Koa = require('koa');const bodyParser = require('koa-bodyparser'); const app = new Koa();const controller = require...

app.js


  
  1. 'use strict';
  2. console.log('Hello world');
  3. const Koa = require('koa');
  4. const bodyParser = require('koa-bodyparser');
  5. const app = new Koa();
  6. const controller = require('./controller');
  7. // parse request body:
  8. app.use(bodyParser());
  9. // add controller:
  10. app.use(controller());
  11. app.listen(5000);
  12. console.log('app started at port 5000...');

controller.js


  
  1. const fs = require('fs');
  2. function addMapping(router, mapping) {
  3. for (var url in mapping) {
  4. if (url.startsWith('GET ')) {
  5. var path = url.substring(4);
  6. router.get(path, mapping[url]);
  7. console.log(`register URL mapping: GET ${path}`);
  8. } else if (url.startsWith('POST ')) {
  9. var path = url.substring(5);
  10. router.post(path, mapping[url]);
  11. console.log(`register URL mapping: POST ${path}`);
  12. } else {
  13. console.log(`invalid URL: ${url}`);
  14. }
  15. }
  16. }
  17. function addControllers(router) {
  18. var fs = require('fs');
  19. var files = fs.readdirSync(__dirname + '\\controllers');
  20. var js_files = files.filter((f) => {
  21. return f.endsWith('.js');
  22. });
  23. for (var f of js_files) {
  24. console.log(`process controller: ${f}...`);
  25. let mapping = require(__dirname + '\\controllers\\' + f);
  26. addMapping(router, mapping);
  27. }
  28. }
  29. module.exports = function (dir) {
  30. let
  31. controllers_dir = dir || 'controllers', // 如果不传参数,扫描目录默认为'controllers'
  32. router = require('koa-router')();
  33. addControllers(router, controllers_dir);
  34. return router.routes();
  35. };

controllers文件夹下的接口接口文件:

./controllers/hello.js


  
  1. 'use strict'
  2. module.exports = {
  3.     'POST /hello/:name': async (ctx, next) => {
  4.         var name = ctx.request.body.name || '';
  5.         ctx.response.body = `<h1>Hello post, ${name}!</h1>`;
  6.     }
  7. };

./controllers/index.js


  
  1. 'use strict'
  2. var fn_index = async (ctx, next) => {
  3. ctx.response.body = `<h1>Index</h1>
  4. <form action="/signin" method="post">
  5. <p>Name: <input name="name" value="koa"></p>
  6. <p>Password: <input name="password" type="password"></p>
  7. <p><input type="submit" value="Submit"></p>
  8. </form>`;
  9. };
  10. var fn_signin = async (ctx, next) => {
  11. var
  12. name = ctx.request.body.name || '',
  13. password = ctx.request.body.password || '';
  14. console.log(`signin with name: ${name}, password: ${password}`);
  15. if (name === 'koa' && password === '12345') {
  16. ctx.response.body = `<h1>Welcome, ${name}!</h1>`;
  17. } else {
  18. ctx.response.body = `<h1>Login failed!</h1>
  19. <p><a href="/">Try again</a></p>`;
  20. }
  21. };
  22. module.exports = {
  23. 'GET /': fn_index,
  24. 'POST /signin': fn_signin
  25. };

文章来源: zzzili.blog.csdn.net,作者:清雨小竹,版权归原作者所有,如需转载,请联系作者。

原文链接:zzzili.blog.csdn.net/article/details/79305544

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。