You need to enable JavaScript to run this app. 后端新手用原生Ajax向Express发POST数据控制台输出空对象求助
优惠活动
大模型
产品
解决方案
定价
更多

后端新手用原生Ajax向Express发POST数据控制台输出空对象求助

问题排查与修正方案

现存核心错误

  • 路由匹配错误:前端发送的是POST请求,但服务端仅定义了GET /路由,POST请求没有对应处理逻辑,不会进入现有GET回调。
  • 参数取值逻辑错误:req.query仅用于读取URL后拼接的查询参数,POST请求的表单提交数据,需要从req.body中读取。
  • 前端请求头缺失:原生XHR发送key=value格式的表单数据时,默认不会自动携带application/x-www-form-urlencoded的内容类型标识,导致body-parser中间件无法识别、解析请求体。

修正后的代码

前端Ajax请求

var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
    console.log(xhttp.responseText);
};
xhttp.open("POST", "http://localhost:8080", true);
// 必须设置正确的请求头,匹配urlencoded解析规则
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhttp.withCredentials = true;
xhttp.send("name=abhishek");

Express服务端代码

var express = require('express');
var cors = require('cors');

var app = express();
app.use(cors({
    credentials:true,
    origin:'http://127.0.0.1:5500'
}));
var PORT = process.env.PORT || 8080;
const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

// 补充对应POST请求的路由,读取req.body而非req.query
app.post('/', function(req, res){
    console.log(req.body);
    // 必须返回响应,否则前端会一直挂起
    res.send({ status: 'success', data: req.body });
});

app.listen(PORT, function(err){
    if (err) console.log(err);
    console.log("Server listening on PORT", PORT);
});

额外注意点

  • 服务端处理路由时必须返回响应,否则前端请求会一直处于pending状态,不会触发onload回调。
  • 确认前端实际运行的地址和CORS配置中的origin完全一致,否则会触发跨域拦截。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 07:36:04