search
HomeWeb Front-enduni-appHow to set the public header in uniapp requrst (two methods)

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)
})

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);
})

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
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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools