首先我们看下官方文档,然后再说说自己的理解和demo
官方文档链接:官方文档-网络请求
我们有几个需要注意的地方:
1、header不能设置referer;
2、method的有效值要大写;
3、数据类型是json(默认json)会做一次JSON.prase;
4、success返回参数里面的header最低版本是1.2.0,必要的时候需要进行兼容处理;
5、网络请求返回值时,低于1.4.0需要兼容处理
那么我们直接从代码中来看:
index.js:
Page({
data:{
info:
""
},
onLoad:
function(e){
var that =
this;
wx.request({
url:
'http://huanqiuxiaozhen.com/wemall/venues/venuesList',
method:
'GET',
data: {},
header: {
'Accept':
'application/json'
},
success:
function (res) {
console.log(
"网络请求成功");
console.log(res.data);
//开发者服务器返回的数据
console.log(res.statusCode);
//开发者服务器返回的 HTTP 状态码
console.log(res.header);
//开发者服务器返回的 HTTP Response Header
var data = res.data.data;
if(res.statusCode ==
200){
that.setData({
info: data
})
}
else{
console.log(
"数据返回错误,状态码:"+res.statusCode);
}
},
fail:
function(res){
console.log(
"网络请求失败");
},
complete:
function(res){
console.log(
"网络请求动作完成");
}
});
}
})
注意的地方就是:header 为 application/json,接口传回来的参数要是json 格式的,否则会报500错误,比如接口返回来的参数是xml则header['content-type'] 要设置为'application/x-www-form-urlencoded'
index.js:
wx.request({
url:
'http://huanqiuxiaozhen.com/wemall/venues/venuesList',
method:
'POST',
data: {},
header:{
"Content-Type":
"application/x-www-form-urlencoded"},
success:
function (res) {
console.log(
"网络请求成功");
console.log(res.data);
//开发者服务器返回的数据
console.log(res.statusCode);
//开发者服务器返回的 HTTP 状态码
console.log(res.header);
//开发者服务器返回的 HTTP Response Header
var data = res.data.data;
if (res.statusCode ==
200) {
that.setData({
info2: data
})
}
else {
console.log(
"数据返回错误,状态码:" + res.statusCode);
}
},
fail:
function (res) {
console.log(
"网络请求失败");
},
complete:
function (res) {
console.log(
"网络请求动作完成");
}
});
为了方便使用,我们把它模块化,封装到request.js里面,然后在app.js里注册成全局函数。
使用的时候,request.js的引用地址自己调整一下。
request.js:
var rootDocment =
'xxxxx';
//你的域名
function req(url, data, cb) {
wx.request({
url: rootDocment + url,
data: data,
method:
'post',
header: {
'Content-Type':
'application/json' },
success:
function (res) {
return
typeof cb ==
"function" && cb(res.data)
},
fail:
function () {
return
typeof cb ==
"function" && cb(
false)
}
})
}
module.exports = {
req: req
}
app.js:
//app.js
var http =
require(
'request.js')
App({
onLaunch:
function () {
//调用API从本地缓存中获取数据
var logs = wx.getStorageSync(
'logs') || []
logs.unshift(Date.now())
wx.setStorageSync(
'logs', logs)
},
getUserInfo:
function (cb) {
var that =
this
if (
this.globalData.userInfo) {
typeof cb ==
"function" && cb(
this.globalData.userInfo)
}
else {
//调用登录接口
wx.login({
success:
function () {
wx.getUserInfo({
success:
function (res) {
that.globalData.userInfo = res.userInfo
typeof cb ==
"function" && cb(that.globalData.userInfo)
}
})
}
})
}
},
globalData: {
userInfo:
null
},
func: {
req: http.req
}
})
使用的demo.js:
var app = getApp()
Page({
data: {
},
onLoad:
function (opt) {
//console.log(opt);
app.func.req(
'/api/getData', {},
function (e) {
console.log(e)
});
}
})
附JS源码
网络请求