uniapp数据请求方式

829 阅读1分钟

uniapp数据请求方式

使用uni.request

uni.request({
    url:'https://woniu.h5project.cn/1.1/classes/Job',
    method:'GET',
    header:{
        "X-LC-Id": "自己的id",
        "X-LC-Key": "自己的key",
        "Content-Type": "application/json"
    },
    success: (res) => {
        console.log(res);
    }
})

自行封装uni.request

// promise的三种状态: pendding处理中  resolve成功   reject失败

import {BASE_URL,ID,KEY} from '../config/index.js'

function http({url,method="GET",data={}}){
  return new Promise((resolve,reject)=>{
    uni.request({
      url:BASE_URL+url,
      method,
      data,
      header:{
        'X-LC-Id': ID, //此处必须使用自己的ID
        'X-LC-Key': KEY,  //此处必须使用自己的Key
        'Content-Type': 'application/json'
      },
      success:(res)=>{
        resolve(res)   //交给then
      },
      fail:(err)=>{
        reject(err)  //交给catch
      }
    })
  })
}

function get(url,data){
  return http({url,method:'GET',data})
}

function post(url,data){
  return http({url,method:'POST',data})
}

function del(url,data){
  return http({url,method:'DELETE',data})
}

export {
  http,
  get,
  post,
  del
}

方法3:使用luch-request第三方库

axios 可能不兼容小程序

import Request from '../js_sdk/luch-request/luch-request/index.js'
import {BASE,ID,KEY} from '../config/index.js'
const http = new Request()
/* config 为默认全局配置*/
http.setConfig((config) => { 
    config.baseURL = BASE+'/1.1/'; /* 根域名 */
    config.header = {
        "X-LC-Id": ID,
        "X-LC-Key": KEY,
        "Content-Type": "application/json"
    }
    return config
})
// 请求拦截器
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
  config.header = {
    ...config.header,
    // a: 1 // 演示拦截器header加参
  }
  console.log('请求拦截器');
  return config
}, config => { // 可使用async await 做异步操作
  return Promise.reject(config)
})
//响应拦截器
http.interceptors.response.use((response) => { /* 对响应成功做点什么 可使用async await 做异步操作*/
  console.log('响应拦截器',response)
  return response
}, (response) => { /*  对响应错误做点什么 (statusCode !== 200)*/
  console.log(response)
  return Promise.reject(response)
})

export default http