继上一篇,现在我们前后端数据库都已经搭建完成了,可以开始我们的前后端数据库通信链调了,在本章内容中,我们将完成整体的基础架构搭建,整个程序会有一个完整的信息回路。
连接数据库
我们首先要在koa项目中连接我们的数据库,以便后续对数据库进行增删改查的操作。
首先启动我们的数据库
$ mongod --dbpath /usr/local/mongodb/data/db
然后在我们的koa项目中安装mongoose第三方包,这是支持我们可以操做数据库的一个插件,官方链接
$ yarn add mongoose
在我们的Koa项目中的app.js文件头部添加以下代码
//app.js
const mongoose = require('mongoose');
const DB_URL = "mongodb://localhost:27017";
mongoose.connect(DB_URL)
mongoose.connection.on('connected', () => {
console.log('mongodb connection open to ' + DB_URL);
})
mongoose.connection.on('error', (error) => {
console.log('mongodb connection error:' + error);
})
mongoose.connection.on('disconnected', () => {
console.log('mongodb connection disconnected');
})
当我们看到以下提示,就显示数据库已经连接成功了
编写正式接口
我们先建立一个modules/blog.js文件,这个文件作为定义数据库的字段,modules这个文件夹可以理解为数据库表的合集。
///modules/blog.js
const mongoose = require("mongoose");
//建立一个新的Schema,里面是数据库的字段,定义类型和必传项
const blogSchema = new mongoose.Schema({
title: { type: String, required: true },
doc: { type: String, required: true },
description: { type: String, required: true },
tag: String,
image: String,
updateAt:String,
});
const Blog = mongoose.model("Blog", blogSchema);
module.exports = Blog;
Then,我们创建controllers/blog.js 文件,这个文件就是接口操作的合集
//controllers/blog.js
"use strict";
const mongoose = require("mongoose");
const Blog = require("../modules/blog");
//获取blog数据
async function GetBlogList(ctx,next){
try{
const data = await Blog.find({})
ctx.body = {
code: 200,
data: data,
}
}catch(err){
console.log(err)
ctx.body= {
code: 500,
message: 'Get Data Error,Please Wait a minute'
}
}
}
//添加数据
async function AddBlog(ctx, next) {
let { title, doc, description, tag, image } = ctx.request.body;
const newBlog = new Blog({
title,
doc,
description,
tag,
image,
updateAt: new Date()
});
try{
await newBlog.save()
ctx.body= {
code: 200,
message: 'Success'
}
}catch(err){
console.log(err)
ctx.body= {
code: 500,
message: 'Add Error,Please Try Again'
}
}
}
module.exports = {
AddBlog,
GetBlogList
};
接下来就是接口文件以及在app.js中去注册接口
//routes/blog.js
const router = require("koa-router")();
const BlogControaller = require("../controllers/blog")
router.prefix("/blog");
router.get("/", BlogControaller.GetBlogList);
router.post("/add", BlogControaller.AddBlog);
module.exports = router;
在app.js中添加以下代码
const blog = require("./routes/blog")
app.use(blog.routes(), blog.allowedMethods());
CMS发布
我们稍微修改一下CMS项目中的代码
const publishNow = () => {
axios.post("http://localhost:8080/blog/add", {
...blogInfo,
doc: doc,
});
};
现在可以看到,我们的数据已经插入到数据库中了
前端接收
我们改一下我们呢博客首页的代码
//index.tsx
import Header from "../components/Header/Header";
import {
HomeBody,
BlogItem,
InfoBox,
Content,
OtherInfo,
CardItem,
} from "../styles/HomePage.styles";
import { Box } from "@chakra-ui/react";
import Image from "next/image";
import handleDate from "@/utils/handleDate";
import testImg from "../assets/1111.png";
function Home(props: any) {
const { data } = props;
return (
<>
<Header />
<HomeBody>
<Box flex={4}>
{data.map((item) => {
return (
<BlogItem key={item._id}>
<Image width={250} height={160} src={item.image} />
<InfoBox>
<h2>{item.title}</h2>
<Content>{item.description}</Content>
<hr />
<OtherInfo>
<div>{item.tag}</div>
<div>{handleDate(item.updateAt)}</div>
</OtherInfo>
</InfoBox>
</BlogItem>
);
})}
</Box>
<Box flex={1}>
<CardItem height="100px"></CardItem>
</Box>
</HomeBody>
</>
);
}
export async function getStaticProps(context) {
const data = await fetch("http://127.0.0.1:8080/blog");
const res = await data.json();
return {
props: {
data: res.data,
}, // will be passed to the page component as props
};
}
export default Home;
现在我们遇到了一个问题 next项目的图片是需要被允许的,我们需要改一下next.config.js文件
/** @type {import('next').NextConfig} */
//xxxx 是图片的域名
const nextConfig = {
reactStrictMode: true,
images: {
domains:['xxxxxxxx']
},
};
module.exports = nextConfig;
现在我们的三端已经通了,可以看到如下效果
总结
本章基本上就是以流水账的形式走下来的,有什么问题或者不懂得欢迎评论区随时问我。
下一步我们就开始弄自动化部署的一套了