You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Axios请求res.headers解构获取x-csrf-token报错求助

How to Get the x-csrf-token from Axios Response Headers

Hey there! Let's break down why your current code is throwing that error and how to properly grab the x-csrf-token you need.

Why Your Current Approaches Aren't Working

First off, it's important to note that axios.get() returns response.headers as a plain JavaScript object, not an array. That's the root of your issues:

  • Object destructuring (let {a,b} = res.headers): This syntax tries to match properties with keys named a and b in the headers object. Since your headers don't have those keys, b ends up as undefined. If you tried to call b() later, that's exactly why you get the "undefined is not a function" error.
  • Array destructuring (let [,b] = res.headers): While modern JS objects are iterable, they iterate over their keys (not values). So this would assign the second key name ('x-csrf-token') to b. If you tried to treat that string as a function, you'd also get a similar error.
  • Also, relying on the "second position" of object properties is risky—object property order isn't guaranteed to stay consistent across all JS environments (even though ES6+ defines a loose order, it's not a safe practice for critical data like CSRF tokens).

The Correct Ways to Get the x-csrf-token

1. Direct Key Access (Recommended)

Since you know the exact header name, just access it directly using bracket notation (perfect for headers with hyphens in their names):

const csrfToken = res.headers['x-csrf-token'];
console.log(csrfToken); // Outputs: 17hoqAWEwVmcN32wYgN9WA==

2. If You Really Need to Get the Second Value (Not Recommended)

If for some reason you must rely on the order (again, this isn't advised), convert the header values to an array first:

const headerValues = Object.values(res.headers);
const secondHeaderValue = headerValues[1];
console.log(secondHeaderValue); // Outputs the x-csrf-token value

Final Note

Stick with direct key access whenever possible—it's more readable, reliable, and avoids unnecessary complexity.

内容的提问来源于stack exchange,提问作者user5228754

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 19:47:50