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 namedaandbin the headers object. Since your headers don't have those keys,bends up asundefined. If you tried to callb()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') tob. 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
相关产品推荐
相关产品推荐

