小程序-formdata传参

项目背景,后端接口要求formData传参:

在util.js文件中封装转化函数,代码如下:

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
const json2Form = json =>{
  var str = [];
  for (var p in json) {
    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));
  }
  return str.join("&");
  console.log(str)
}

module.exports = {
  formatTime: formatTime,
  json2Form: json2Form
}

使用页面:

首先:var util = require('../../utils/util')

设置header也很重要,代码如下:

wx.request({
        url: host +'/pingan/chatbot',
        method:'POST',
        data: util.json2Form({
          version: 0.1,
          clientType: 'web',
          robotId: '1030',
          userId: 'test1',
          sessionId: '10231451574',
          question: nowV
        }),
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success:function(res){
          console.log(res)
          if (res.data.status&&res.data.status.state === '1'){
            // 文字转语音
            this.play(res.data.content.answer)
            let nid = 'id_1' + Date.parse(new Date()) / 1000
            console.log(nid)
            let fData = { id:nid,content: res.data.content.answer, me: false }
            speakT.push(fData)
            that.setData({
              speakT: speakT,
              toView: nid
            }) 
          }
        },
        fail:function(res){
          console.log(res)
        }
      })