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

如何在浏览器中传递Bearer Token调用基于SimpleJWT的Rest API?

嘿,我来帮你搞定这个问题!在浏览器里调用带SimpleJWT认证的API,核心就是把Bearer Token正确塞进请求头里就行,下面给你几种常用的实现方式,适配不同的前端场景:

1. 原生JavaScript(Fetch API)

如果用浏览器原生的Fetch发送请求,直接在请求配置里添加Authorization头就行,格式是Bearer + 空格 + 你的JWT令牌:

// 假设你已经从登录接口拿到了令牌,存在变量里
const jwtToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';

fetch('https://your-api-domain.com/api/your-endpoint/', {
  method: 'GET', // 根据需求换成POST/PUT/DELETE等
  headers: {
    'Authorization': `Bearer ${jwtToken}`,
    // 如果是POST请求要传JSON数据,记得加这个头
    'Content-Type': 'application/json'
  }
})
.then(response => {
  if (!response.ok) {
    throw new Error('请求失败');
  }
  return response.json();
})
.then(data => console.log('返回数据:', data))
.catch(err => console.error('请求出错:', err));

2. 使用Axios库(前端开发常用)

如果你的项目用了Axios,有两种更便捷的方式添加令牌:

单个请求手动加头

适合只有个别接口需要认证的场景:

import axios from 'axios';

const jwtToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';

axios.get('https://your-api-domain.com/api/your-endpoint/', {
  headers: {
    'Authorization': `Bearer ${jwtToken}`
  }
})
.then(res => console.log('返回数据:', res.data))
.catch(err => console.error('请求出错:', err));

全局自动加头(推荐)

如果大部分接口都需要认证,直接全局配置Axios,让所有请求自动带上令牌,省得每个请求都写:

import axios from 'axios';

// 从本地存储(比如localStorage)取出之前登录时保存的令牌
const jwtToken = localStorage.getItem('userToken');

// 设置全局默认请求头
axios.defaults.headers.common['Authorization'] = `Bearer ${jwtToken}`;

// 之后所有Axios请求都会自动带上认证头
axios.get('https://your-api-domain.com/api/your-endpoint/')
.then(res => console.log('返回数据:', res.data))
.catch(err => console.error('请求出错:', err));

甚至可以用Axios的请求拦截器,动态获取令牌(比如令牌过期后自动刷新的场景):

axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem('userToken');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

3. 额外注意事项

  • 确保你的JWT令牌是有效的:SimpleJWT的access token有过期时间,过期后需要用refresh token重新获取新的access token
  • 跨域问题:如果前端和后端域名不同,要在Django后端配置CORS(推荐用django-cors-headers库),并确保CORS_ALLOW_HEADERS包含Authorization,否则浏览器会拦截带自定义头的请求
  • 令牌存储:建议把令牌存在localStorage或sessionStorage里,不要存在明文Cookie中(如果用Cookie的话要设置HttpOnly,但前端就拿不到了,适合后端渲染场景)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 13:02:39