項目背景,後端接口要求formData傳參:web
在util.js文件中封裝轉化函數,代碼以下:json
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')session
設置header也很重要,代碼以下:app
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) } })