云迈博客

您现在的位置是:首页 > 前端技术 > node.js > 正文

node.js

使用 koa快速搭建 web服务

吴志云2022-04-06node.js249
01需要使用到的依赖包koa用于node.js的富有表现力的HTTP中间件框架@koa/router路由中间件koa-bodyparser请求解析如postkoa-art-templ

01 需要使用到的依赖包

koa 用于 node.js 的富有表现力的 HTTP 中间件框架
@koa/router 路由中间件
koa-bodyparser 请求解析 如post
koa-art-template Koa艺术模板视图模版引擎 渲染中间件
koa-static Koa静态文件服务中间件

02安装依赖

npm i koa @koa/router koa-bodyparser art-template koa-art-template koa-static -S

03编写代码

创建 js文件如 index.js

const Koa=require("koa");
const router=require("@koa/router")();
const bodyParser=require("koa-bodyparser");
const serve = require('koa-static');
const path = require('path');
const render = require('koa-art-template');
const app=new Koa();
app.use(bodyParser());
app.use(serve(__dirname + '/static'))//静态文件目录

render(app, {
  root: path.join(__dirname, 'views'),// html 根路径
  extname: '.html',// 文件 后缀 可自定义
  debug: process.env.NODE_ENV !== 'production'
});

router.get("/", async ctx=>{
   await  ctx.render("index")//views目录 下面的 index.html
})

router.post("/getInfo", async ctx=>{
    获取 post请求 参数
    const info=ctx.request.body;
     console.log(info)
      ctx.body={ //返回数据
      user:"郭德纲",
      age:"男",
      sex:"未知",
      info:info
      }
})
router.get("/getUser", async ctx=>{
    获取 get请求 参数
    const info=ctx.query;
     console.log(info)
      ctx.body={ //返回数据
      user:"于谦",
      age:"男",
      sex:"未知",
      info:info
      }
})
router.get("/getUser/:path", async ctx=>{//动态路由
    获取 动态路由ctx.params 请求 参数
    const info=ctx.query;
     console.log(info)
      ctx.body={ //返回数据
      user:"于谦",
      age:"男",
      sex:"未知",
      info:info
      }
})
app.use(router.routes()).use(router.allowedMethods());

app.listen(3000,()=>{
console.log("服务器已启动")
})

04运行

命令行 npm run index.js
可使用 pm2.js 保持后台启动 和 集群
浏览器 打开 127.0.0.1:3000

发表评论

评论列表

  • 这篇文章还没有收到评论,赶紧来抢沙发吧~