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

ExpressJS 接收前端POST请求时req.body显示为空的问题求助

问题原因

前后端代码均存在错误,具体问题如下:

  • 前端请求发送逻辑错误
    • XMLHttpRequest的send()方法无法直接传入普通JavaScript对象,原生XHR会将该类对象自动转为[object Object]字符串,服务端解析工具无法识别该格式,导致请求体为空。
    • 未显式设置请求头Content-Type: application/json,服务端无法判断请求体的格式类型,无法正确解析。
    • 前端请求地址占位符SERVER_URL未替换为实际的服务端接口地址,且前端传递的请求体字段为username、password,和服务端读取的字段名不匹配。
  • 服务端配置&取值逻辑错误
    • CORS跨域中间件的注册顺序错误,当前放在了post /data路由之后,跨域请求无法正常应用响应头,会被浏览器拦截。
    • 服务端读取请求体时使用req.body.u、req.body.p,和前端传递的字段名不一致,因此无法读到正确值。
修复方案

前端JS代码修复

let u = document.getElementById("u");
let p = document.getElementById("p");
let msg = document.getElementById("msg");

let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log("登录请求响应:", this.responseText)
    }
};

//login function triggered when user clicks login
function login() {
  // 字段名和服务端读取逻辑对齐
  const data = {
    "u": u.value,
    "p": p.value
  }
  // 同域部署直接写接口路径,跨域部署写完整服务端地址
  xhttp.open("POST", "/data", true);
  // 声明请求体格式为JSON
  xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  // 把JS对象转为JSON字符串后再发送
  xhttp.send(JSON.stringify(data))
}

服务端代码修复

// environment variables
const client = process.env['MAIN_CLIENT'];

// imports
const express = require('express');
const path = require('path');

//init
const app = express();

// 新版express内置请求体解析,不需要单独引入body-parser,保留原有body-parser代码也可正常运行
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// 跨域中间件移到所有路由前面,确保所有请求都能应用跨域配置
app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", client);
  // 新增允许的请求头配置,避免JSON格式请求的预检请求被拦截
  res.setHeader("Access-Control-Allow-Headers", "Content-Type");
  next();
});

app.get('/', (req, res) => {
  res.sendFile(`${__dirname}/index.html`)
})

app.post(`/data`, (req, res) => {
  console.log(req.body)
  const u = req.body.u;
  const p = req.body.p;
  const data = process.env; 
  console.log("----------------") 
  
  if (data[u] == p) {
    console.log(`\n-/-/-/-/-/-/-/-/-/-/-/-/\nA user just logged in.\nUsername: ${u}\n-/-/-/-/-/-/-/-/-/-/-//-/ \n`)
    res.send(true)
  }
  else{
    console.log("no")
    res.send(false)
  }
});

app.listen(3000, () => {console.log('ready!')});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 20:36:03