Fetch 请求需手动设置 Authorization 头,常用 Bearer Token 格式为“Bearer ${token}”,Basic 认证需 Base64 编码凭据,且服务端须在 CORS 响应头中声明 Authorization 才能通过预检。

Fetch 请求携带 Authorization 凭证,关键在于正确设置 headers 选项,并确保凭证格式符合服务端要求(通常是 Bearer token 或 Basic base64string)。
设置 Authorization 请求头
在 fetch() 的配置对象中,通过 headers 字段添加 Authorization 头。注意:必须手动指定,浏览器不会自动带上它(不像某些 Cookie 场景)。
- Bearer Token(最常见):
Authorization: Bearer eyJhbGciOi... - Basic 认证:
Authorization: Basic dXNlcjpwYXNz(用户名密码经 Base64 编码) - 自定义方案(如 API Key):
Authorization: ApiKey abc123
完整 fetch 示例(含 Authorization)
以下是一个带 Bearer Token 的 POST 请求示例:
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
fetch('/api/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({ name: 'Alice' })
})
.then(res => res.json())
.then(data => console.log(data));
⚠️ 注意:Content-Type 和 Authorization 都需显式声明;Bearer 后面要留一个空格。
Java Maven 项目审查工作流的通用输入处理。当 Java Maven 项目以 ZIP压缩包或 GitLab 仓库 URL 形式提供且需要...时使用。
立即学习“Java免费学习笔记(深入)”;
避免常见错误
- 忘记加
Bearer前缀(只传 token 字符串 → 401) - token 存储在 localStorage/sessionStorage 中但未检查是否存在,导致空字符串被发送
- 跨域请求时,若服务端未在
Access-Control-Allow-Headers中声明Authorization,浏览器会预检失败 - 使用
credentials: 'include'时,Authorization头仍需手动设置(二者不冲突,但用途不同)
封装成可复用的请求函数
为减少重复,建议封装一个带默认认证头的 fetch 工具:
function authFetch(url, options = {}) {
const token = localStorage.getItem('auth_token');
return fetch(url, {
...options,
headers: {
'Content-Type': 'application/json',
'Authorization': token ? `Bearer ${token}` : '',
...options.headers
}
});
}
// 使用
authFetch('/api/profile')
.then(res => res.json());
这样既保证了灵活性,又避免每次手动拼接头信息。

















