您好,欢迎访问一九零五行业门户网

uniapp requrst怎么设置公共头部(两种方法)

在开发过程中,我们经常会用uniapp来构建跨平台的应用程序。uniapp是一个基于vue.js的开源框架,它能够将vue.js的内核和一些跨平台的能力打包在一起,提供了一套完整的开发体验。而在开发过程中,我们经常会需要发送网络请求来获取数据,此时,我们就需要设置一些公共头部参数,以此来保障请求的准确、有效。
uniapp中,我们可以使用封装好的uni.request来发送网络请求。uni.request具有很好的跨平台性能,在uniapp中封装了原生的xmlhttprequest和原生的axios扩展,可以用于发起http/https请求。而对于设置公共头部参数,有以下两种常用方法。
方法一:在request的options中设置
// main.jsvue.prototype.$http = function (url, data, method) {  let token = uni.getstoragesync('token');  let header = {    'authorization': token,    'content-type': 'application/json'  };  return uni.request({    url,    data,    method,    header  })}// 调用this.$http('/api/user', { id: 123, name: 'tom' }, 'get').then(res => {  console.log(res)})
其中,在main.js中定义了$ttp方法,在options中设置了公共头部参数,调用时传入具体的参数即可。
方法二:通过拦截器统一设置
// request.jsexport function request(opts) {  let token = uni.getstoragesync('token');  let header = {    'authorization': token,    'content-type': 'application/json'  };  const interceptor = {    request: (opts) => {      opts.header = header;      return opts;    },    response: (res) => {      const { statuscode, data } = res;      if (statuscode === 200) {        return data;      } else {        uni.showtoast({          title: '请求失败',          icon: 'none'        })        return promise.reject(res);      }    }  }  uni.addinterceptor(interceptor);  return uni.request(opts).finally(() => {    uni.removeinterceptor(interceptor);  })}// 调用request({  url: '/api/user?id=123&name=tom',  method: 'get'}).then(res => {  console.log(res);})
在此方法中,我们定义了一个request函数,在函数中通过拦截器拦截请求并设置公共头部参数,然后通过uni.request来发起请求。在调用request时,只需要传入具体的参数即可。
综上所述,我们可以看到,uniapp中设置公共头部参数的方法并不难,只需要在uni.request的options中设置即可,也可以通过拦截器统一设置,这样可以提高代码的复用性,减少重复代码的编写,是一个不错的选择。
以上就是uniapp requrst怎么设置公共头部(两种方法)的详细内容。
其它类似信息

推荐信息