很多时候,我们前端工作涉及到的都是关于前端这一块的内容,如何来完成一个全栈的项目呢?关于后端的逻辑,前端更好的是通过node来实现,做好一个全栈项目也就不是那么难了。
先来写一个demo
效果图
实现来哪些功能:主要实现了标签的增删改查
项目介绍
前端代码文件放在 app
文件夹下,后端代码放在 server
下,前端不做介绍了,主要讲解下后端node的实现。
入口文件index.js
const express = require('express')
//引入中间件
const bodyParser = require('body-parser')
const tag = require('./router.js')
const app = express()
const port = 3000
// 请求体解析中间件
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use('/api', tag)
app.listen(port, () => console.log('正在监听 3000 端口'))
其中的router.js
// 引入express模块
const express = require('express')
// 定义路由级中间件
const router = express.Router()
// 引入数据模型模块
const Tag = require('./tag')
// 查询全部
router.get('/list', (req, res) => {
Tag.find({})
.sort({ update_at: -1 })
.then(tags => {
res.json(tags)
})
.catch(err => {
res.json(err)
})
})
// 根据id查询
router.get('/list/:id', (req, res) => {
Tag.findById(req.params.id)
.then(tag => {
res.json(tag)
})
.catch(err => {
res.json(err)
})
})
// 新增
router.post('/add', (req, res) => {
//使用Tag model上的create方法储存数据
Tag.create(req.body, (err, tag) => {
if (err) {
res.json(err)
} else {
res.json(tag)
}
})
})
// 编辑
router.put('/edit/:id', (req, res) => {
Tag.findOneAndUpdate(
{ _id: req.params.id },
{
$set: {
name: req.body.name,
url: req.body.url,
},
},
{
new: true,
}
)
.then(tag => res.json(tag))
.catch(err => res.json(err))
})
// 删除
router.delete('/delete/:id', (req, res) => {
Tag.findOneAndRemove({
_id: req.params.id,
})
.then(tag => res.send(`${tag.name}删除成功`))
.catch(err => res.json(err))
})
module.exports = router
其中的tag.js
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017', err => {
if (err) {
console.log('mongodb 连接失败')
} else {
console.log('mongodb 连接成功')
}
})
// 定义表,其中字段有name和url
const tagSchema = mongoose.Schema(
{
name: String,
url: String,
},
{ collection: 'tag' }
)
// 导出model模块
module.exports = mongoose.model('tag', tagSchema)
涉及到的知识点
了解express(www.expressjs.com.cn/)
了解mogoose (www.mongoosejs.net/)
关于部署
前端的部署主要是配置nginx的代理
location /api {
proxy_pass http://localhost:3000;
}
后端的部署主要是安装mogodb数据库,然后安装pm2管理进程
通过pm2启动项目