koa学习(2)

前端模板引擎的渲染 可以用ejs模板

const render = require('koa-ejs');
//配置模板引擎
render(app,{
    root:path.join(__dirname,'views'),
    layout:'layout',
    viewExt:'html',
    cache:false,
    debug:false
})

配置模板引擎。 定义根路径下的'views'文件夹为需要渲染的模板,后缀名为.html

定义渲染

router.get("/",index);

可以将index单独的抽离出来

//将index抽取出来单独保存 //函数声明
async function index(ctx) {
    await ctx.render("index",{
        title:"i love",
        things:things
    });
}

index.html页面如下

<h1>ccccccc</h1>
<h1><%- title %></h1>
<ul class="list-group">
<% things.forEach(thing => { %>
<li class="list-group-item">
    <%= thing.name %>
</li>

<% }) %>
</ul>

<% 表示模板引擎内容 <% 说明需要转义 而 <%= 说明需要渲染出 不需要转义

重定向

//添加路由方法
router.post("/add",add);
async function add(ctx){
    console.log("12345");
 const body = ctx.request.body;
 console.log(body);
 ctx.redirect("/");
}

连接moogoose数据库

 

var mongoURI = require("./config/keys").mongoURI;
//连接数据库
mongoose.connect(mongoURI,
{ useNewUrlParser: true })
.then(() => {
console.log("connected");
}).catch((err) => {
    console.log(err);
});

在config文件夹下的key.js中 将mongoURI暴露出去

module.exports = {
    mongoURI:"mongodb://lab421:[email protected]:28117/dspider2?authSource=admin"
};

新建router文件夹 在里面定义接口的一些函数。需要引用路由 并进行定义

var Router = require("koa-router");
var router = new Router();
//test
router.get("/test",async (ctx) => {
    ctx.status = 200;
    ctx.response.body = {"msg":"hello world"};
});
router.post("/register",async(ctx) => {
console.log(ctx.request.body);
ctx.response.body = {name:'ckq'};
})
module.exports = router.routes();

随后将路由暴露出去即可

在app.js中引入

//引入user.js
const users = require("./routes/api/user");

随后定义路由

//配置路由
router.use("/api/user",users);

这样在访问api/user的时候 便都会跳转到users函数中进行操作。随后根据对应的test路由或者register路由进行跳转。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章