当前位置:首页 > React

react如何附带tokens

2026-02-26 08:20:27React

在React中附带tokens(如认证令牌)通常用于API请求的身份验证。以下是几种常见的方法:

使用axios发送请求附带token

通过axios的拦截器或请求配置,可以在请求头中添加token。例如:

import axios from 'axios';

const api = axios.create({
  baseURL: 'https://api.example.com',
});

api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// 使用api实例发送请求
api.get('/user').then(response => console.log(response));

使用fetch API附带token

fetch API可以通过手动设置请求头来附带token:

fetch('https://api.example.com/user', {
  method: 'GET',
  headers: {
    'Authorization': `Bearer ${localStorage.getItem('token')}`,
    'Content-Type': 'application/json',
  },
})
.then(response => response.json())
.then(data => console.log(data));

封装自定义hook

可以创建一个自定义hook来统一处理附带token的逻辑:

import { useState, useEffect } from 'react';

function useApi(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(url, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
        },
      });
      const result = await response.json();
      setData(result);
      setLoading(false);
    };
    fetchData();
  }, [url]);

  return { data, loading };
}

使用context管理token

通过React的Context API全局管理token,避免重复从存储中读取:

import { createContext, useContext } from 'react';

const AuthContext = createContext();

function AuthProvider({ children }) {
  const token = localStorage.getItem('token');

  return (
    <AuthContext.Provider value={{ token }}>
      {children}
    </AuthContext.Provider>
  );
}

function useAuth() {
  return useContext(AuthContext);
}

// 在组件中使用
function ProtectedComponent() {
  const { token } = useAuth();
  // 使用token发送请求
}

使用高阶组件(HOC)

对于类组件,可以通过高阶组件自动注入token:

function withAuth(WrappedComponent) {
  return function(props) {
    const token = localStorage.getItem('token');
    return <WrappedComponent {...props} token={token} />;
  };
}

// 使用高阶组件
class UserProfile extends React.Component {
  componentDidMount() {
    // 使用this.props.token发送请求
  }
}

export default withAuth(UserProfile);

react如何附带tokens

标签: reacttokens
分享给朋友:

相关文章

react如何

react如何

React 基础概念 React 是一个用于构建用户界面的 JavaScript 库,专注于组件化开发。通过虚拟 DOM 和高效的渲染机制,React 能够实现高性能的 UI 更新。 安装 R…

react moment如何使用

react moment如何使用

安装 react-moment 通过 npm 或 yarn 安装 react-moment: npm install react-moment 或 yarn add react-moment 基本…

react如何运行

react如何运行

运行React项目的步骤 安装Node.js 确保系统已安装Node.js(建议版本12以上),可从官网下载并安装。Node.js自带npm包管理器,用于后续依赖安装。 创建React项目 使用官方…

react如何收录

react如何收录

React 收录方法 React 的收录主要涉及搜索引擎优化(SEO)和预渲染技术。由于 React 是单页应用(SPA),默认情况下内容由 JavaScript 动态生成,可能导致搜索引擎爬虫难以收…

如何配置react

如何配置react

配置React项目的步骤 安装Node.js和npm 确保系统已安装Node.js(包含npm)。可通过官网下载并安装最新版本。安装完成后,运行以下命令验证版本: node -v npm -v 创建…

react如何安装

react如何安装

安装React的步骤 确保已安装Node.js(建议版本12或更高),可通过以下命令检查版本: node -v npm -v 使用Create React App快速搭建项目(推荐): npx…