【问题标题】:Problem with dynamic request header in axios templateaxios模板中的动态请求标头问题
【发布时间】:2022-01-07 12:32:19
【问题描述】:

在我的 react 应用程序中,我创建了一个 api.js 文件,该文件使用 axios.create 创建了一个 api 对象并将其导出为默认值。因此,我使用该模板来发出 API 请求。问题是,创建的 axios api 对象中的标头之一必须是动态的。 例如,请参阅下面的 locale 标头:

一开始可能是这样的:

export default api = axios.create({
    baseURL: process.env.REACT_APP_API_URL,
    headers: {
      post: {
        "Content-Type": "application/json;charset=utf-8",
        "Access-Control-Allow-Origin": "*",
        locale: "en",
      },
      get: {
        locale: "en",
      },
    },
  });

但一段时间后它可以更新到其他语言环境,例如 "en" 应该更改为 "fr"。我该如何更新它,并确保它在更新时会在每个导入 api 的地方发生变化。

我不能使用 ContextApi 等,因为我也需要在 index.js 文件中使用那个 api,因为它不是一个反应组件,所以不支持使用钩子。

【问题讨论】:

  • Access-Control-Allow-Origin 是来自服务器的 response 标头。它不属于您的请求,通常很可能会导致 CORS 错误。另外,在 Axios 中发布 JS 对象时默认的 content-type 是application/json,所以你通常不需要设置它

标签: javascript api axios locale


【解决方案1】:

听起来像是Axios interceptors 的工作...

import axios from "axios"

// some kind of storage for your locale
let locale = "en"

// some way of changing it
export const setLocale = (newLocale) => {
  locale = newLocale
}

const api = axios.create({
  baseURL: process.env.REACT_APP_API_URL,
})

// register a synchronous request interceptor
api.interceptors.request.use(config => ({
  ...config,
  headers: {
    ...config.headers,
    locale // merge the "locale" into the request config headers
  }
}), null, { synchronous: true })

export default api

另外,Access-Control-Allow-Origin 是来自服务器的响应标头。它不属于您的请求,通常很可能会导致 CORS 错误。

另外,在 Axios 中发布 JS 对象时默认的 content-type 是application/json 所以you typically don't need to set it。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-04
    • 2020-10-15
    • 2018-04-06
    • 1970-01-01
    • 2021-11-30
    • 2023-03-12
    • 1970-01-01
    • 2021-09-06
    相关资源
    最近更新 更多