Home Web Front-end uni-app How to set the public header in uniapp requrst (two methods)

How to set the public header in uniapp requrst (two methods)

Apr 17, 2023 am 10:30 AM

During the development process, we often use UniApp to build cross-platform applications. UniApp is an open source framework based on Vue.js. It can package the Vue.js core and some cross-platform capabilities together, providing a complete development experience. During the development process, we often need to send network requests to obtain data. At this time, we need to set some public header parameters to ensure the accuracy and effectiveness of the request.

In UniApp, we can use the encapsulated uni.request to send network requests. uni.request has good cross-platform performance. It encapsulates the native XMLHttpRequest and the native axios extension in UniApp and can be used to initiate HTTP/HTTPS requests. For setting public header parameters, there are the following two common methods.

Method 1: Set in the options of the request

// main.js
Vue.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)
})
Copy after login

Among them, the $ttp method is defined in main.js, the public header parameters are set in the options, and the specific parameters are passed in when calling parameters.

Method 2: Unified setting through interceptor

// request.js
export 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);
})
Copy after login

In this method, we define a request function, in which the request is intercepted through the interceptor and the public header parameters are set, and then passed uni.request to initiate a request. When calling request, you only need to pass in specific parameters.

To sum up, we can see that it is not difficult to set public header parameters in UniApp. You only need to set them in the options of uni.request, or you can also set them uniformly through interceptors. This can improve the reusability of the code and reduce the writing of repeated code, which is a good choice.

The above is the detailed content of How to set the public header in uniapp requrst (two methods). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1229
24