关于javascript:文章小程序全栈开发从入门到上线第4节发布文章

6次阅读

共计 3477 个字符,预计需要花费 9 分钟才能阅读完成。

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


# 微信小程序 appid
WECHAT_MINI_APP_ID=wx1f196182a0f906e7
# 微信小程序 secret
WECHAT_MINI_APP_SECRET=74d89**********e1e47c9f66aaeab

# mysql 数据库配置
MYSQL_HOST=localhost
MYSQL_USER=root
MYSQL_PASSWORD=12345678
MYSQL_DATABASE=bidu
MYSQL_PORT=3306
MYSQL_CHARSET=utf8mb4_unicode_ci


# 动态文件地址 
STATIC_URL=http://localhost:3000

2. 小程序增加文章页面

具体代码,可查看 github 上的源码。
在小程序端新增一个编辑文章的页面 home/add,并在home 页面增加导航。
富文本编辑是用的微信富文本组件,预览示例
其中须要留神的是,图片上传接口,如下:

3. 增加文章新增接口

首页,咱们要新建一张文章的表,字段 status 默认值为2,如图:

另外,文章的详情内容,用 mongodb 来存储。所以,咱们要新增 .env 的内容,退出:
没有用户名和明码,能够不填

...
# mongodb 数据库配置
MONGODB_HOST=localhost
MONGODB_USER=root
MONGODB_PASSWORD=123456
MONGODB_DATABASE=bidu
MONGODB_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 地址

正文完
 0