1.增加图片上传接口
新增一个文件夹,server/static/articles/
专门用来存文章图片的。而后,在server/app.js
里,批改动态文件地址
/* app.js */...app.use(express.static(path.join(__dirname, './static')))...
新增server/routes/upload.js
,
/* upload.js */const express = require('express')const {saveFile} = require('../utils/file')const multer = require('multer')const path = require('path')let uploadRouter = express.Router()let upload = multer({dest: path.join(__dirname, '../uploads/')})//图片上传示例 web端/** 如果须要验证用户,加上authUse 就行。 前端也要记得header带上token */uploadRouter.post('/articles', upload.single('file'), async function(req, res, next) { const {file} = req let baseUrl = saveFile(file, '/articles') res.json({ path: baseUrl, url: process.env.STATIC_URL + baseUrl })})module.exports = uploadRouter
上传的图片,将会保留在static/articles
目录下
在server/app.js
外面,也要引入这两个
/* app.js */...var uploadRouter = require('./routes/upload');...app.use('/upload', uploadRouter);
创立server/utils/file.js
文件夹,进行上传图片时的解决
/* file.js */const fs = require('fs')const path = require('path')// 文件保留,删除等操作// file为 multer 包解决后的file。const saveFile = (file, localPath, fileName) => { let data = fs.readFileSync(file.path) let extname = file.originalname.substring(file.originalname.lastIndexOf('.')+1) let savename = fileName ? (fileName + '.' + extname) : file.originalname fs.writeFileSync(path.join(__dirname, '../static' + localPath + '/' + savename), data) fs.unlinkSync(path.join(__dirname, '../uploads/' + file.filename)) let baseUrl = localPath + '/' + savename return baseUrl}// 删除文件const deleteFile = (pathUrl) => { if (!fs.existsSync(path.join(__dirname, '../static' + pathUrl))) { return true } fs.unlinkSync(path.join(__dirname, '../static' + pathUrl)) return true}module.exports = { saveFile, deleteFile}
在server/.env
外面,退出动态文件地址,退出后,代码如下
# jwt 密钥,任意字符串JWT_TOKEN_SECRET=ZM_j3@faF93Mdaie2f# jwt 生成的 token 的过期工夫,单位秒JWT_TOKEN_EXPIRATION_TIME=3600# 微信小程序 appidWECHAT_MINI_APP_ID=wx1f196182a0f906e7# 微信小程序 secretWECHAT_MINI_APP_SECRET=74d89**********e1e47c9f66aaeab# mysql 数据库配置MYSQL_HOST=localhostMYSQL_USER=rootMYSQL_PASSWORD=12345678MYSQL_DATABASE=biduMYSQL_PORT=3306MYSQL_CHARSET=utf8mb4_unicode_ci# 动态文件地址 STATIC_URL=http://localhost:3000
2.小程序增加文章页面
具体代码,可查看github
上的源码。
在小程序端新增一个编辑文章的页面home/add
,并在home
页面增加导航。
富文本编辑是用的微信富文本组件,预览示例
其中须要留神的是,图片上传接口,如下:
3.增加文章新增接口
首页,咱们要新建一张文章的表,字段status
默认值为2
,如图:
另外,文章的详情内容,用mongodb来存储。所以,咱们要新增.env
的内容,退出:
没有用户名和明码,能够不填
...# mongodb 数据库配置MONGODB_HOST=localhostMONGODB_USER=rootMONGODB_PASSWORD=123456MONGODB_DATABASE=biduMONGODB_PORT=27017
创立server/routes/articles.js
,办法和之前一样,而后,新增文章的接口如下:
// 新增articlesRouter.post('/add', authUse, async (req, res, next) => { const {user, body} = req const {title, cover_url, html} = body let nowTime = getTime('date_time') // 将根底数据,保留在mysql let tempAid = (await mysql.set('articles', { title: title, cover_url: cover_url, uid: user.id, created_at: nowTime })).data.insertId // 将文章内容保留在 mongodb await mongodb.set('articles', { title: title, html: html, article_sql_id: tempAid, cover_url: cover_url, nickname: user.nickname, avatar_url: user.avatar, created_at: nowTime, status: 2, }) res.json({ status: 2, message: '胜利' })})
能够看到,下面代码中,有一个authUse
中间件,这个就是之前在server/utils/jwt.js
里写的,通过申请时的header
中的受权信息,token,来判断,该用户是否登录,如果是登录的,且没过期,就能够通过id获取用户的详情信息。因为在中间件authUse
里,咱们把user
赋值到req
上的,所以,两头执行之后的代码,就能够从req
中,很不便的获取到用户信息了。即const {user} = req
。
小程序里/pages/home/add/add.js
,申请接口如下:
如果要验证用户身份,就要带token,我是每个接口都独自写的,其实齐全能够本人封装成对立申请。
/* add.js */ addOne(){ let {title, coverPath, html} = this.data console.log('title, c, f', title, coverPath, html) wx.request({ url: app.config.api + '/articles/add', method: 'POST', header: { 'Authorization': `Bearer ${wx.getStorageSync('TOKEN')}` }, data: { title: title, cover_url: coverPath, html: html }, success: ({data}) => { console.log('dddddddd', data) } }) }
这里,新增性能就能够了。
demo地址