cookies 小程序

2023-09-04  本文已影响0人  糖醋里脊120625
// import * as Api from './api'
import { getLocalUserInfo } from '../unit/userInfo'



// export const MAINLINK = 'https://sy-food.net/';
export const MAINLINK = 'https://nginx.etmobile.net/';
//  export const MAINLINK = 'http://172.16.92.54/';



const getRequestHeader = () => {
  console.log(getLocalUserInfo())
  // let token =  "7346152e-41c3-4e12-93c6-ace6201bd4eb";
  let token = getLocalUserInfo() ? getLocalUserInfo().token : "";
  return token ? {
    "content-type": 'application/json;charset=UTF-8',
    'cookie':token
  } : {
    "content-type": 'application/json;charset=UTF-8',
    // "Access-Token":""
  }
}




// 请求传入reqData参数   返回promise对象 因为全局请求我每次返回的类型都是不一样的,所以我直接any
export const doRequestAction = (reqData) => {
  // 将不存在的参数字段使用默认值进行替换
  let req = {  ...reqData }

  return new Promise((resolve, reject) => {
    //检测是否开启loading层 
    if (req.loadIng) {
      wx.showLoading({
        title: "数据加载中",
        icon: "none"
      })
    }
    wx.request({
      url: req.url, //引入我的接口是特殊声明的,所以我就不检测http/https了
      method: req.method,
      data: req.data,
      header: {
        
        'content-type':'application/json;charset=UTF-8',
        'cookie':wx.getStorageSync('Set-Cookie')+";"
     },
      success(res) {
        if(req.url.includes("supplychain-apis/account/login") || req.url.includes("supplychain-apis/account/change-login") ){
          if (res.header['Set-Cookie'] != '') {
            var cookieStr = "";
  
            var cookieArr = [];
  
            res.cookies.forEach((item, index, array) => {
              cookieArr.push(item.split(";")[0]);
  
            });
            cookieStr = cookieArr.join(";");
            wx.setStorageSync("Set-Cookie", cookieStr);           
          }
        }

        
        



        wx.hideLoading()
        const code = res.data.code;
        console.log(code)
        
        
        if (code == 200) {  // 请求成功
          resolve(res.data);
          
          
        } else if (res.data.code == 401) {
          wx.showToast({
            icon: 'none',
            title: 'Token失效,请重新登录',
          })
          wx.redirectTo({ url: '/pages/login/login?EditData='+'Backinto' });
          reject('运行时错误,请稍后再试')
        } else {

          if(req.popUpTips== undefined){
            console.log(req.popUpTips)
            wx.showToast({
              icon: 'none',
              title: res.data.message,
            })

          }
          
          reject('运行时错误,请稍后再试'); // 其他异常
        }
      },
      fail(err) {
        wx.showToast({
          icon: 'none',
          title: err.errMsg,
        })
        wx.hideLoading()
        // 请求失败
        reject(err)
      }
    })
  })
}

上一篇下一篇

猜你喜欢

热点阅读