我们可以新建一个 server 文件夹 ,里面创建一个server.js 文件,来集中处理我们项目中用到的请求:
var server = function(url, type, params) {
return new Promise((resolve, reject) => {
wx.request({
url: 'http://localhost:7001/' + url,
data: params || {},
method: type || 'GET',
success: function(res) {
resolve(res.data)
},
fail: function(res) {
reject(res)
}
})
})
}
// get请求
server.get = function(url, params) {
return new Promise((resolve, reject) => {
wx.request({
url: 'http://localhost:7001/' + url,
data: params || {},
method: 'GET',
success: function (res) {
resolve(res.data)
},
fail: function (res) {
reject(res)
}
})
})
}
export default server
在需要发起请求的页面中 引入这个文件:
import server from '../server/index.js'
getArticles() {
server.get('articles',{pageIndex: 1, pageSize: 10}).then(res => {
// console.log(res)
// 因为小程序的数据不是双向绑定的所以不能直接赋值
// this.data.articles = res.data
// console.log(this.data.articles)
this.setData({
articles: res.data
})
})
},