- POST 注意事項
標準模板
var util = require('../../utils/util.js')
wx.request({
url: 'https://URL',
data: {},
method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
// header: {}, // 設(shè)置請求的 header
success: function(res){
// success
},
fail: function() {
// fail
},
complete: function() {
// complete
}
})
注意幾點:
1.method 必須參數(shù)必須是大寫的
2.GET方式請求時,data:傳輸json類型,但是在POST 請求方式中勃蜘,data如果直接傳json數(shù)據(jù)歪脏,服務(wù)器會接受不到數(shù)據(jù)
所以在post請求需要特殊處理一下
wx.request({
url: 'http://kuzoutianya.com/xxxx',
data: Util.json2Form({
name:"酷走天涯",
text:"你好"
}),
method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
header: {"Content-Type": "application/x-www-form-urlencoded"}, // 設(shè)置請求的 header
success: function(res){
console.log(res);
},
fail: function() {
// fail
},
complete: function() {
// complete
}
})
}
特殊處理1:
>header: {"Content-Type": "application/x-www-form-urlencoded"}
特殊處理2:
>data: Util.json2Form({
name:"酷走天涯",
text:"你好"
})
上面的Util.json2Form 的作用是將json數(shù)據(jù)進行網(wǎng)絡(luò)編碼拼接
結(jié)果如下 name=%E5%BE%90%E6%9D%B0&text=%E4%BD%A0%E5%A5%BD
實現(xiàn)方式
util.js 文件
>function json2Form(json) {
var str = [];
for(var p in json){
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));
}
console.log(str.join("&"));
return str.join("&");
}
module.exports = {
json2Form:json2Form,
}
encodeURIComponent函數(shù):可把字符串作為URI 組件進行編碼