前端每个接口都需要传递UserId的实现方式比较

396 阅读4分钟

如果每个接口都需要前端传递一个 userId,有几种方式可以使这个过程更简单和一致:

1. 全局请求拦截器

  • 在使用 Axios、Fetch API 或其他类似库时,可以配置全局请求拦截器。这样每次发送请求时,userId 会自动附加到请求中,而无需在每个请求中手动添加。

使用 Axios 举例:

import axios from 'axios';

const userId = '12345'; // 从用户登录信息或其他地方获取

// 创建一个 axios 实例
const axiosInstance = axios.create();

// 设置请求拦截器
axiosInstance.interceptors.request.use(config => {
    config.headers['X-User-ID'] = userId; // 添加到请求头
    // 或者 config.params['userId'] = userId; // 添加到 URL 参数中
    return config;
});

// 之后的请求都会自动带上 userId
axiosInstance.get('/api/user').then(response => console.log(response.data));
axiosInstance.post('/api/another-endpoint', { data: 'test' }).then(response => console.log(response.data));

使用 Fetch API 举例:

如果使用 fetch,可以封装一个自定义的 fetch 函数:

const userId = '12345';

function customFetch(url, options = {}) {
    options.headers = {
        ...options.headers,
        'X-User-ID': userId
    };
    return fetch(url, options);
}

// 之后的请求都使用 customFetch
customFetch('/api/user')
    .then(response => response.json())
    .then(data => console.log(data));

customFetch('/api/another-endpoint', {
    method: 'POST',
    body: JSON.stringify({ data: 'test' }),
    headers: {
        'Content-Type': 'application/json'
    }
}).then(response => response.json()).then(data => console.log(data));

2. 使用 Context 或全局状态管理

  • 如果你使用的是 React、Vue.js 或 Angular,可以通过 Context 或全局状态管理(如 Redux、Vuex)来存储 userId,然后在请求中自动附加它。

在 React 中使用 Context:

import React, { createContext, useContext } from 'react';

const UserContext = createContext();

export function UserProvider({ children }) {
    const userId = '12345';
    return (
        <UserContext.Provider value={userId}>
            {children}
        </UserContext.Provider>
    );
}

export function useUserId() {
    return useContext(UserContext);
}

// 在组件中使用
import { useUserId } from './UserContext';

function fetchData() {
    const userId = useUserId();
    fetch('/api/user', {
        headers: {
            'X-User-ID': userId
        }
    }).then(response => response.json()).then(data => console.log(data));
}

3. 封装统一的 API 请求函数

  • 封装一个统一的 API 请求函数,所有 API 请求都通过这个函数发出,这样可以确保 userId 一直传递。
const userId = '12345';

function apiRequest(endpoint, options = {}) {
    options.headers = {
        ...options.headers,
        'X-User-ID': userId
    };
    return fetch(endpoint, options);
}

// 所有请求都使用 apiRequest
apiRequest('/api/user')
    .then(response => response.json())
    .then(data => console.log(data));

apiRequest('/api/another-endpoint', {
    method: 'POST',
    body: JSON.stringify({ data: 'test' }),
    headers: {
        'Content-Type': 'application/json'
    }
}).then(response => response.json()).then(data => console.log(data));

4. 通过中间件处理

  • 在后端通过中间件来自动识别和处理请求的用户身份信息,这样前端可以在登录时传递 userId,后续所有请求都无需手动传递。

5. 使用 JWT 或 Cookie

  • userId 编码在 JWT token 中,前端只需在每次请求时附上 token,后端解码 token 获取 userId。或者将 userId 存储在 Cookie 中,自动随请求发送。

通过这些方法,可以避免在每个请求中手动传递 userId,从而简化前端代码,减少出错的可能性。


华丽的分割线


我选择的是使用JWT或Cookie的方式。那么这种方式怎么把userId编码到token中呢? 如果每个接口都需要前端传递一个 userId,有几种方式可以使这个过程更简单和一致:

1. 全局请求拦截器

  • 在使用 Axios、Fetch API 或其他类似库时,可以配置全局请求拦截器。这样每次发送请求时,userId 会自动附加到请求中,而无需在每个请求中手动添加。

使用 Axios 举例:

import axios from 'axios';

const userId = '12345'; // 从用户登录信息或其他地方获取

// 创建一个 axios 实例
const axiosInstance = axios.create();

// 设置请求拦截器
axiosInstance.interceptors.request.use(config => {
    config.headers['X-User-ID'] = userId; // 添加到请求头
    // 或者 config.params['userId'] = userId; // 添加到 URL 参数中
    return config;
});

// 之后的请求都会自动带上 userId
axiosInstance.get('/api/user').then(response => console.log(response.data));
axiosInstance.post('/api/another-endpoint', { data: 'test' }).then(response => console.log(response.data));

使用 Fetch API 举例:

如果使用 fetch,可以封装一个自定义的 fetch 函数:

const userId = '12345';

function customFetch(url, options = {}) {
    options.headers = {
        ...options.headers,
        'X-User-ID': userId
    };
    return fetch(url, options);
}

// 之后的请求都使用 customFetch
customFetch('/api/user')
    .then(response => response.json())
    .then(data => console.log(data));

customFetch('/api/another-endpoint', {
    method: 'POST',
    body: JSON.stringify({ data: 'test' }),
    headers: {
        'Content-Type': 'application/json'
    }
}).then(response => response.json()).then(data => console.log(data));

2. 使用 Context 或全局状态管理

  • 如果你使用的是 React、Vue.js 或 Angular,可以通过 Context 或全局状态管理(如 Redux、Vuex)来存储 userId,然后在请求中自动附加它。

在 React 中使用 Context:

import React, { createContext, useContext } from 'react';

const UserContext = createContext();

export function UserProvider({ children }) {
    const userId = '12345';
    return (
        <UserContext.Provider value={userId}>
            {children}
        </UserContext.Provider>
    );
}

export function useUserId() {
    return useContext(UserContext);
}

// 在组件中使用
import { useUserId } from './UserContext';

function fetchData() {
    const userId = useUserId();
    fetch('/api/user', {
        headers: {
            'X-User-ID': userId
        }
    }).then(response => response.json()).then(data => console.log(data));
}

3. 封装统一的 API 请求函数

  • 封装一个统一的 API 请求函数,所有 API 请求都通过这个函数发出,这样可以确保 userId 一直传递。
const userId = '12345';

function apiRequest(endpoint, options = {}) {
    options.headers = {
        ...options.headers,
        'X-User-ID': userId
    };
    return fetch(endpoint, options);
}

// 所有请求都使用 apiRequest
apiRequest('/api/user')
    .then(response => response.json())
    .then(data => console.log(data));

apiRequest('/api/another-endpoint', {
    method: 'POST',
    body: JSON.stringify({ data: 'test' }),
    headers: {
        'Content-Type': 'application/json'
    }
}).then(response => response.json()).then(data => console.log(data));

4. 通过中间件处理

  • 在后端通过中间件来自动识别和处理请求的用户身份信息,这样前端可以在登录时传递 userId,后续所有请求都无需手动传递。

5. 使用 JWT 或 Cookie

  • userId 编码在 JWT token 中,前端只需在每次请求时附上 token,后端解码 token 获取 userId。或者将 userId 存储在 Cookie 中,自动随请求发送。

通过这些方法,可以避免在每个请求中手动传递 userId,从而简化前端代码,减少出错的可能性。