溫馨提示×

uniapp怎么請求后端接口數據

小億
531
2024-02-05 17:42:40
欄目: 編程語言

要使用uniapp請求后端接口數據,可以使用uni.request方法。

首先,在uniapp項目中的main.js文件中引入uni.request方法:

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

然后,在utils文件夾下創建一個request.js文件,定義uni.request方法:

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

現在你可以在組件中使用uniRequest方法來請求后端接口數據了。例如,在一個組件的methods中使用uniRequest方法獲取數據:

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

這樣就可以在uniapp中請求后端接口數據了。根據后端接口的要求,可以在uniRequest方法中設置請求的url、methoddata等參數。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女