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

如何在Node.js(Express框架)中获取前端AJAX请求传递的变量

问题原因

你当前代码无法拿到参数主要有3个核心问题:

  • 前端AJAX的data参数格式错误:GET请求传参需要传入键值对结构,直接传变量值会导致服务端无法识别对应的参数名
  • 服务端参数取值对象错误:GET请求携带的查询参数挂载在req.query对象下,你用的req.params是用来获取路由动态段参数的(比如路由定义为/api/:id时,才能从req.params.id拿到值)
  • 同一路由GET /同时承担返回页面和处理AJAX请求的逻辑会冲突,建议拆分独立接口处理AJAX请求
调整后代码

前端 search.html

<script>
    // 注意:使用$.ajax需要先引入jQuery库,没有引入的话请先在页面里添加jQuery引入
    function postData() {
        var country = document.getElementById("Country").value;
        console.log(country);
        $.ajax({
            type: "GET",
            // 改成独立的接口地址,和返回页面的路由区分开
            url: 'http://localhost:8080/getCountry',
            // 改成键值对格式,参数名为country
            data: {country: country},
            dataType:'text',
            success: function(data) {
                console.log('success data: ', data);
            }
        });
    }
</script>

服务端 server.js

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

app.listen(8080, function() {
    console.log('Listening on 8080.');
});

// 原路由保留,负责返回页面
app.get('/', function(req, res) {
    res.sendFile(__dirname + '/search.html');
});

// 新增独立接口,处理前端的AJAX请求
app.get('/getCountry', function(req, res) {
    // 从req.query里取country参数
    const country = req.query.country;
    console.log('前端传递的country值:', country);
    // 可以给前端返回自定义内容
    res.send(`已收到国家参数:${country}`);
});
验证方式

启动服务后,在页面输入国家值触发postData方法,即可在服务端控制台看到对应的参数输出,前端也会收到服务端的返回内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 09:45:09