//npm下载项
npm i koa koa-router koa-bodyparser koa-static koa-views ejs koa2-cors mongodb koa-session koa-multer
npm i koa2-cors 解决跨域
//引入
const Koa = require("koa"); //koa
const Router = require("koa-router"); //koa的路由
const static = require("koa-static"); //静态资源加载
const bodyParser = require("koa-bodyparser"); //解析post请求
const views = require("koa-views"); //koa-页面模板
const session = require("koa-session"); //服务器存储
const multer = require("koa-multer"); //文件上传
const db = require("./moudle/db") //引入数据库
const cors = require("koa2-cors")//解决跨域
//实例化
const app = new Koa();
const router = new Router();
//注入依赖模块
app.use(cors())解决跨域
app.use(static(__dirname + "/public")) //静态资源
app.use(bodyParser()) //解析post请求
app.use(views("views", { extension: "ejs" })) //页面模板
app.use(router.routes()).use(router.allowedMethods()) //解析路由
//开启服务
app.listen(3000, _ => {
console.log("server running at http://localhost:3000")
});
==================================================
router.get('',async ctx=>{})搭路由
ctx.query 获取浏览器地址参数
ctx.querystring获取浏览器地址参数字符串
ctx.params获取动态路由地址变量
ctx.url获取路径
ctx.redirect('/') 重定向,重新定义路由跳转
ctx.body="ko2"//相当于输出
next()//往下执行
})中间件
================================
//接口
router.get("/movieList", async ctx => {
const pageIndex = Number(ctx.query.pageIndex)
const pageSize = Number(ctx.query.pageSize)
let pageCount = await db.getCount("movie", {})
pageCount = Math.ceil(pageCount / pageSize)
if (pageIndex && pageSize) {
const movieList = await db.find("movie", {}, pageIndex, pageSize)
ctx.body = {
success: 1,
data: {
pageIndex,
pageSize,
pageCount,
movieList
},
error: null
}
} else {
ctx.status = 400;
ctx.body = {
success: 0,
data: null,
error: {
errCode: 27373, //
message: "当前请求参数异常"
}
}
}
})
router.get("/indexBanner", async ctx => {
const data = await db.find("banner", {})
ctx.body = {
success: 1,
data,
error: null
};
})
router.post("/login", async ctx => {
ctx.set("content-type", "application/json;charset=utf-8")
const { username, password } = ctx.request.body
const result = await db.find("users", { username });
const r = result[0]
if (result.length && r.password !== password) {
ctx.body = JSON.stringify({
success: 0,
error: {
message: "账户或密码错误"
}
})
} else if (result.length && r.password === password) {
ctx.body = JSON.stringify({
success: 1,
error: null
})
ctx.session.username = r.username
} else {
ctx.body = JSON.stringify({
success: 0,
error: {
//27081 用户名不存在
// errCode: 27081
message: "用户名不存在"
}
})
}
})
router.post("/register", async ctx => {
ctx.set("content-type", "application/json;charset=utf-8")
const { username, password } = ctx.request.body
ctx.session = null;
ctx.session.username = username
const result = await db.find("users", { username })
if (result.length) {
ctx.body = JSON.stringify({
success: 0,
error: {
message: "账户名重复"
}
})
} else {
const insert = await db.insert("users", ctx.request.body);
console.log(insert)
ctx.body = JSON.stringify({
success: 1,
error: null
})
}
})
===================================