网络请求:简单的封装一个请求

我们可以新建一个 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
      })
    })
  },

 

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章