小程序的request 能否全局添加header?
发布于 6 年前 作者 xiexiulan 18643 次浏览 来自 问答

目前想给所有接口的header添加一个key,不知小程序是否有提供全局处理的方法

5 回复

在app.js的globalData中定义一个header,然后加一个处理所有请求的函数就可以了。例如:

fetch: function (options) {
    let header = this.header
    return new Promise((resolve, reject) => {
      const requestTask = wx.request({
        method: options.method,
        header: header,
        url: options.url,
        data: options.data,

        success: function (res) {

           resolve(res)

       },

        fail: function (res) {},
        complete: function () {}
      })
    })
  }


const request = function (config = {}) {

       config.header={

       'content-type':'application/x-www-form-urlencoded'

}


wx.requset(config);

}


开发者自己包装一个 request 即可

自己封装一层

回到顶部