fetch获取的bearer token传入后续请求返回401错误问题排查
问题原因与修复方案
- 缺失Bearer前缀:标准Bearer认证的Authorization头格式为
Bearer <token字符串>,你直接将token值赋值给Authorization头没有加前缀,后端无法正确解析认证信息,这是触发401的核心原因。 - 多余请求头配置:第二个GET请求无请求体,不需要配置
Content-Type: application/json,部分严格的后端校验会拦截该不符合规范的请求。 - 多余JSON解析操作:已经通过
response.json()将响应转成了JS对象,后续无需再调用JSON.parse(),重复解析会抛出语法错误。 - 缺失接口状态校验:未判断/auth接口的响应状态,若该接口返回错误响应,你读取到的token值为undefined,也会触发401。
- 可选凭证配置:如果接口依赖Cookie做校验,fetch默认不会携带跨域Cookie,需要补充
credentials: 'include'配置。
修正后代码
const tokenApi = "./auth"; const listingsApi = "./listings"; let clientHeaders = new Headers(); let raw = JSON.stringify({ email: "fake@account.com", password: "12345", }); clientHeaders.append("Content-Type", "application/json"); let req = { method: "POST", headers: clientHeaders, body: raw, redirect: "follow", // 如果需要带Cookie可以打开下面的注释 // credentials: 'include' }; fetch(tokenApi, req) .then((response) => { // 先判断认证接口请求是否成功 if (!response.ok) { throw new Error('认证接口请求失败,状态码:' + response.status) } return response.json() }) .then((result) => { if (!result.token) { throw new Error('认证接口未返回有效token') } return fetch(listingsApi, { method: "GET", headers: { // 补充Bearer前缀 Authorization: `Bearer ${result.token}`, }, // 如果需要带Cookie可以打开下面的注释 // credentials: 'include' }); }) .then((response) => { if (!response.ok) { throw new Error('列表接口请求失败,状态码:' + response.status) } return response.json(); }) .then((data) => { // 已经是JS对象,直接打印即可 console.log(data); }) .catch((error) => { console.log("error: ", error); });
内容的提问来源于stack exchange,提问作者VanCoon
相关产品推荐
相关产品推荐

