前端模板引擎的渲染 可以用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路由進行跳轉。