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

如何将LocalStorage中的值作为参数传入Axios请求?

问题解决:React向Express传递LocalStorage用户ID

核心问题原因

你在React中通过POST请求将用户ID放在请求体中,但后端错误地使用req.params.id获取参数——req.params是用来读取URL路径参数(比如/getRandomCard/:id这种格式)的,而POST请求的JSON参数应该从req.body中读取。

第一步:修复后端代码

首先确保Express已经配置了解析JSON请求体的中间件(否则req.body会是undefined),然后修改参数获取方式:

const express = require('express');
const app = express();

// 必须在路由之前添加这个中间件,解析JSON格式的请求体
app.use(express.json());

app.post('/getRandomCard', async function (req, res) {
    const id = req.body.id; // 改为从req.body获取ID

    console.log('userid= ', id); // 现在能正确拿到前端传递的ID了

    // 后续数据库操作逻辑...
});

第二步:React代码优化建议

你的React代码存在一些可以改进的地方,以下是优化后的完整代码:

import React, { useEffect, useState } from 'react';
import axios from "axios"; // 移除重复的Axios导入,保持统一

const Cards = () => {
    const [card, setCard] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [errorMsg, setErrorMsg] = useState(null);
    // 将LocalStorage的字符串ID转为数字,避免后续数据库操作类型不匹配
    const userId = Number(localStorage.getItem("id"));

    useEffect(() => {
        async function fetchRandomCard() {
            setIsLoading(true);
            setErrorMsg(null);
            try {
                // 先校验ID是否存在,避免无效请求
                if (!userId) throw new Error("未获取到用户ID");
                
                const response = await axios.post(
                    'http://localhost:3001/getRandomCard',
                    { id: userId }
                );
                setCard(response.data);
            } catch (err) {
                console.error('请求失败:', err);
                setErrorMsg(err.message || "获取卡牌失败");
            } finally {
                setIsLoading(false);
            }
        }

        // 只有当用户ID有效时才发起请求
        userId && fetchRandomCard();
    }, [userId]); // 把userId加入依赖数组,ID变化时自动重新请求

    // 加载状态展示
    if (isLoading) return <div className="text-center">正在获取卡牌...</div>;
    // 错误状态展示
    if (errorMsg) return <div className="text-center text-danger">{errorMsg}</div>;

    return (
        <div>
            <div>
                {card.map(aCard => (
                    <div className="text-center" key={aCard.name}>
                        {aCard.name}
                        <img 
                            alt={`Image de ${aCard.name}`} 
                            className="activator" 
                            src={`http://localhost/lfl/inc/img/players-ico/${aCard.name}`} 
                            style={{ width: '100%' }}
                        />
                    </div>
                ))}
            </div>
        </div>
    );
};

export default Cards;

优化点说明

  • 移除重复的axios导入,避免模块冗余
  • 添加加载状态和错误提示,提升用户体验
  • 对LocalStorage的ID做类型转换,避免字符串ID在数据库操作中出现问题
  • 增加ID有效性校验,防止无效请求
  • 将userId加入useEffect依赖数组,当用户ID变化时自动重新发起请求
  • 使用模板字符串替代字符串拼接,代码更简洁易读

额外注意事项

  1. CORS跨域问题:如果React运行在3000端口,Express在3001端口,需要安装cors中间件解决跨域:
    npm install cors
    
    然后在Express中添加:
    const cors = require('cors');
    app.use(cors());
    
  2. 安全性:后端不要直接信任前端传来的ID,需要额外验证该ID是否存在于数据库中,防止恶意伪造请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 13:48:25