axios拦截器和默认标头有什么区别?

发布于 2025-01-14 01:32:00 字数 282 浏览 3 评论 0原文

我很好奇 axios 拦截器和默认标头之间的区别。

我想在标题中添加授权。

我知道我可以使用 axios 拦截器和默认标头管理授权标头。 (为所有 axios 请求附加授权标头

我不确定何时分别使用拦截器和默认标头。

难道只是axios提供了两种方法吗?

I'm curious about the difference between axios interceptor and default header.

I want to add authorization in header.

I know I can manage authorization header with axios interceptor and default header.
(Attach Authorization header for all axios requests)

I'm not sure when to use the interceptor and default header respectively.

Is it simply that axios provides two methods?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

许久 2025-01-21 01:32:00

默认标头是静态分配的。您放入其中的值必须在代码执行时已知。

axiosOrInstance.defaults.headers.common["x-value"] = "some value you must know";

拦截器是根据请求/响应执行的函数。这意味着他们可以访问之前可能不可用的值,甚至可以访问特定于当前请求的值。

axiosOrInstance.interceptors.request.use(config => ({
  ...config,
  headers: {
    ...config.headers,
    "x-value": "whatever"
  }
}), null, {
  synchronous: true,
  runWhen: config => config.url === "only/run/for/this/url"
})

它们也可以是异步的,并在解析之前进行其他异步调用

axiosOrInstance.interceptors.request.use(async config => {
  const someValue = await getSomeAsyncValue()
  return {
    ...config,
    headers: {
      ...config.headers,
      "x-value": someValue
    }
  };
});

Default headers are assigned statically. The values you place into them must be known at the time your code executes.

axiosOrInstance.defaults.headers.common["x-value"] = "some value you must know";

Interceptors are functions that execute per request / response. This means they can access values that might not have been available earlier or even values specific to the current request.

axiosOrInstance.interceptors.request.use(config => ({
  ...config,
  headers: {
    ...config.headers,
    "x-value": "whatever"
  }
}), null, {
  synchronous: true,
  runWhen: config => config.url === "only/run/for/this/url"
})

They can also be asynchronous and make other async calls before resolving

axiosOrInstance.interceptors.request.use(async config => {
  const someValue = await getSomeAsyncValue()
  return {
    ...config,
    headers: {
      ...config.headers,
      "x-value": someValue
    }
  };
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文