微信小程序封装http(request)

在小程序开发管理界面配置域名

点击详情查看域名信息

 

 

在utils下创建http.js

function request(options) {
    // 请求拦截器
    //  ...
    // 1. 加一些统一的参数,或者配置
    if (!options.url.startsWith("https://") && !options.url.startsWith("http://")) {
      options.url = "https://showme2.myhope365.com" + options.url
    }
      // 默认的请求头
    let header = {
  "content-type": "application/x-www-form-urlencoded",
  // 加上统一的cookie
  "cookie": wx.getStorageSync("cookie") || ""
    };
    if (options.header) {
      header = {
        ...header,
        ...options.header
      }
    }
  
    return new Promise((reslove, reject) => {
      // 调用接口
      wx.request({
        // 默认的配置
        // 加载传入的配置
        ...options,
        header,
        success(res) {
          // 响应拦截器,所有接口获取数据之前,都会先执行这里
          //  1. 统一的错误处理
          if (res.statusCode != 200) {
            wx.showToast({
              title: '服务器异常,请联系管理员',
            })
          }
  
          reslove(res)
        },
        fail(err) {
          reject(err)
        }
      })
    })
  }

  export function get(url, options = {}) {
    return request({
      url,
      ...options
    })
  }
  
  export function post(url, data, options = {}) {
    return request({
      url,
      data,
      method: "POST",
      ...options
    })
  }
  
  

使用post

引入

import { post } from "../../utils/http";
post('https://showme2.myhope365.com/api/login',
        {
            username:this.data.userName,
            password:this.data.passWord,
            rememberMe:true
        }
        ).then(res => {
            console.log(res);
        })

get

引入

import {
    get
} from "../../utils/http";
get(`https://showme2.myhope365.com/api/cms/article/open/detail/${options.id}`).then(res => {
            console.log(res.data.data);
            this.setData({
                content: res.data.data
            })
        })

 

posted @ 2021-10-12 22:53  从入门到入土  阅读(933)  评论(0编辑  收藏  举报