• Lv0
    粉丝0

积分15 / 贡献0

提问1答案被采纳0文章0

作者动态

    使用ohos_axios 2.2.1-rc.0 最新版 post请求无法动态设置header

    open_9527 显示全部楼层 发表于 2024-4-26 11:30:04
    
    export const instance = axios.create({
      baseURL: BASE_URL,
      timeout: TIME_OUT,
      timeoutErrorMessage: TIME_OUT_MESSAGE,
      headers: { 'id': '001', 'token': 'xxx' },
    })
    
    const requestInterceptors = instance.interceptors.request.use(
      async (config: InternalAxiosRequestConfig) => {
        let headers = config.headers
        headers["header1"] = 'interceptor_001'
        headers["header2"] = 'interceptor_002'
        headers["header3"] = '003'
        // let requestConfig: AxiosRequestConfig = config.data as AxiosRequestConfig
        // if (requestConfig.headers) {
        //
        // }
        // LogUtils.debug('网络请求Request', ` RequestData requestConfig= ${JsonUtils.stringify(requestConfig)}`)
        LogUtils.debug('网络请求Request', ` RequestData requestData= ${JsonUtils.stringify(config)}`)
        LogUtils.debug('网络请求Request', ` RequestData headers= ${JsonUtils.stringify(config.headers)}`)
        LogUtils.debug('网络请求Request', ` RequestData params= ${JsonUtils.stringify(config.params)}`)
        LogUtils.debug('网络请求Request', ` RequestData data= ${JsonUtils.stringify(config.data)}`)
    
        return config
      },
      (error: AxiosError) => {
        LogUtils.debug("网络请求RequestError", `RequestError=${error.toString()} `)
        return error
      }
    )
    
    
    export function post<T>(config: AxiosRequestConfig): Promise<T> {
      config.headers={'post_header':'post_header'}
      return instance.post<object, T>(config.url, config)
    }
    
    
    export function get<T>(config: AxiosRequestConfig): Promise<T> {
      config.headers={'get_header':'get_header'}
      return instance.get<object, T>(config.url, config)
    }
    
    
    1.在使用GET请求的时候 header 是有效的 但是在post请求中是无效的
    2.response 拦截器中的 onRejected 错误响应无法回调到 接口请求的外层中
    您尚未登录,无法参与评论,登录后可以:
    参与开源共建问题交流
    认同或收藏高质量问答
    获取积分成为开源共建先驱

    精彩评论6

    马迪

    沙发 发表于 2024-4-26 14:29:06
    没太看明白问题。 跟最新版本相关吗,之前的OK?

    open_9527

    发表于 2024-4-26 15:02  IP属地: - 中国江苏省扬州市 中国电信IDC

    回复 马迪: 就是 我有个post请求需要单独添加一个header,我直接配置时无效的,get请求是可以的。版本目前用的最新版,之前版本不知道

    【1 条回复】

    hyacinth养花人

    板凳 发表于 2024-4-26 18:25:26

    使用ohos_axios 2.2.1-rc.0 最新版 post请求无法动态设置header

    fakename.png
    axios.post 第一个参数是url,第二个参数是请求体,第三个参数是配置项。
    axios.get第一个参数是url,第二个参数是配置项。

    你封装得不太对



    马迪

    发表于 2024-5-4 12:42  IP属地: 贵州省贵阳市

    回复 hyacinth养花人: +1

    open_9527

    发表于 2024-5-7 14:18  IP属地: - 中国上海市 中国电信IDC

    回复 hyacinth养花人: 看了下入参,传错了

    【2 条回复】

    旺旺崔冰冰

    地板 发表于 2024-5-9 18:33:11
    您好,最新版是可以动态设置的,详情参考第三方库中的eftool库中二次封装的efAxios中有demo
    https://gitee.com/yunkss/ef-tool ... ios/EfClientApi.ets

    Copyright   ©2023  OpenHarmony开发者论坛  京ICP备2020036654号-3 |技术支持 Discuz!

    返回顶部