• home > webfront > AppDev > taro >

    taro本地开发接口调试以及cookies认证鉴权问题解决

    Author:zhoulujun Date:

    taro小程序 Taro request原来的h5登录逻辑无法用,发现cookies没有被发送。官方文档credentials配置无效,只有 xhrFields: {withCredentials: true}才有效果

    taro 在h5端调试,只需在 config/index.js  h5配置项 增加

    h5: {
      publicPath: '/',
      staticDirectory: 'static',
      devServer: {
        // host: 'dev.bkapps.oa.com',
        disableHostCheck: true,
        host: '0.0.0.0',
        port: 10086,
        proxy: [
          {
            context: ['weixin'],
            target: "http://stag-dot-tgem.bkapps-sz.oa.com/",
            changeOrigin: true,
            secure: false,
            ws: false,
          }
        ]
      }
    }

    webserver怎么配,具体查看:https://webpack.js.org/configuration/dev-server/

    但是,如果是小程序调试,发现cookie 并没有发送。

    Taro.request 默认不发送cookies,所以没有保持会话

    具体查看:https://taro-docs.jd.com/taro/docs/apis/network/request/request

    所以需要手动存储cookies,具体代码如下:

    import Taro from '@tarojs/taro'
    import { HTTP_STATUS } from '../constants/status'
    import logError from '../utils/error'
    import { publicUrl } from '../../env'
    import { HttpResponse } from '../constants/commonType'
    class Http {
      requestQueue: Record<string, any> = {}
    
      request(path: string, method, data: any, cancelToken) {
        console.log('Taro.getStorageSync(\'cookies\')')
        let cookies = Taro.getStorageSync('cookies')
        const url: string = publicUrl + path
        return new Promise((resolve, reject) => {
          const source = Taro.request(
            {
              url,
              data,
              method,
              mode: 'cors',
              credentials: 'include',// 官方的文档说加个,但是并无卵用
              xhrFields: {withCredentials: true},//带上cookies
              header: {
                'content-type': 'application/json', // 默认值
                'Cookie': cookies
                // 'Cookie': Taro.getStorageSync('Cookies')
              },
              success(response: Taro.request.SuccessCallbackResult & Res) {
                console.log(response)
                setCookie(response)
                if (response.statusCode === HTTP_STATUS.NOT_FOUND) {
                  return logError('api', '请求资源不存在')
                } else if (response.statusCode === HTTP_STATUS.BAD_GATEWAY) {
                  return logError('api', '服务端出现了问题')
                } else if (response.statusCode === HTTP_STATUS.FORBIDDEN) {
                  return logError('api', '没有权限访问')
                } else if (response.statusCode === HTTP_STATUS.AUTHENTICATE) {
                  Taro.clearStorage()
                  Taro.navigateTo({
                    url: '/pages/login/index'
                  })
                  return logError('api', '请先登录')
                } else if (response.statusCode === HTTP_STATUS.SUCCESS) {
                  const res: HttpResponse = response.data
                  if (res.result) {
                    resolve(res.data)
                  } else {
                    reject(res)
                    Taro.showToast({
                      title: res.message,
                      icon: 'success',
                      duration: 2000
                    })
                  }
                }
              },
              complete(res) {
                console.log(res)
              },
              fail(res: Record<string, any>) {
                logError('api', '请求失败', res)
                console.log(res)
                reject(
                  {
                    code: res.status,
                    result: false,
                    message: '网络请求失败',
                  }
                )
              }
            },
          )
          if (cancelToken) {
            //TODO
          }
        })
    
      }


    就这样,okay

    不过,还是后台信不过单token认证呗



    转载本站文章《taro本地开发接口调试以及cookies认证鉴权问题解决》,
    请注明出处:https://www.zhoulujun.cn/html/webfront/AppDev/taro/8705.html