Uniapp Backend Data Request Tutorial

You can use the uni.request method to request data from the backend interface in Uniapp.

Firstly, import the uni.request method in the main.js file of the uniapp project.

import { uniRequest } from '@/utils/request'
Vue.prototype.$uniRequest = uniRequest

Next, create a request.js file in the utils folder, and define the uni.request method.

export const uniRequest = (url, method = 'GET', data = {}) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: url,
      method: method,
      data: data,
      header: {
        'content-type': 'application/json'
        // 这里可以设置其他header
      },
      success: res => {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          reject(res)
        }
      },
      fail: err => {
        reject(err)
      }
    })
  })
}

Now you can use the uniRequest method in components to request backend API data. For example, in a component’s methods, you can use the uniRequest method to fetch data.

methods: {
  getData() {
    this.$uniRequest('/api/data').then(res => {
      console.log(res)
    }).catch(err => {
      console.log(err)
    })
  }
}

This way, you can request backend interface data in Uniapp. According to the requirements of the backend interface, you can set the url, method, and data parameters in the uniRequest method.

bannerAds