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

React项目中如何通过axios将userEmail变量作为查询参数传递给后端查询MongoDB数据

实现步骤

1. 修改Landing.js调用逻辑

把当前登录用户的userEmail作为参数传入surveyApiGet方法:

// userEmail变量从登录态/全局上下文/状态管理等位置获取
surveyApiGet(userEmail)
        .then(response => {
          // 原有业务逻辑
        })
        .catch(err => {
          console.log(err.message);
        });

2. 修改api.js的封装函数

接收userEmail参数,将其作为GET请求的查询参数传递给后端:

export async function surveyApiGet (userEmail) {
    let response = await axios.get('http://localhost:6000/', {
      params: {
        userEmail: userEmail
      }
    });
    return response.data;
}

axios会自动把params参数拼接为URL查询串,最终请求地址为http://localhost:6000/?userEmail=xxx@xx.com格式

3. 修改后端dateApi.js的查询逻辑

从请求中获取前端传递的userEmail参数,替换原有的全匹配正则查询条件:

let MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";
const express = require('express');
const app = express();

app.use(express.json());

app.get('/', function (req, res) {
    // 从GET请求查询参数中提取userEmail
    const userEmail = req.query.userEmail;
    // 增加参数校验,拦截非法请求
    if (!userEmail) {
      return res.status(400).json({msg: "缺少用户邮箱参数"});
    }
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db("manderleydb");
        // 替换查询条件为匹配当前用户邮箱
        var query = { userId : userEmail };
        dbo.collection("manderleySurveyCompleted").find(query).sort({ date: 1}).limit(1)
            .toArray(function(err, result) {
                if (err) throw err;
                console.log(result);
                db.close();
                // res.json会自动序列化对象,不需要额外调用JSON.stringify
                res.status(200).json(result);
        });
    });
});

app.listen(6000, () => {
    console.log('listening on port 6000');
});
额外优化建议
  • 请确认数据库manderleySurveyCompleted集合中存储用户邮箱的字段名为userId,如果实际存储邮箱的字段名不同,需要同步修改query中的键名
  • 生产环境建议复用MongoDB连接池,不要每次接口请求都新建连接,避免性能问题
  • 敏感用户信息建议后续改用POST请求+请求体传递,或者增加接口鉴权逻辑避免越权查询

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:45:03