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

使用经典JavaScript Ajax发送请求,Node.js后端无法获取Payload问题求助

问题分析与解决方案

你的Ajax调用存在格式错误,导致Payload没有被正确发送到后端,具体问题和修复方式如下:

核心错误原因

你设置了请求头Content-Type: application/x-www-form-urlencoded,但直接将JavaScript对象传给了xhttp.send()。对于该Content-Type,XMLHttpRequest要求传入URL编码的键值对字符串(例如username=xxx&password=123),而非原始对象。直接传对象会被自动转成[object Object]字符串,后端自然无法解析出有效数据。

修复前端Ajax代码

添加一个工具函数,将Payload对象转换为符合要求的URL编码格式:

function objectToFormUrlEncoded(obj) {
  return Object.keys(obj).map(key => 
    `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`
  ).join('&');
}

function ajax(endpoint, method, payload) {
  const xhttp = new XMLHttpRequest();
  const url = 'http://localhost:3000/' + endpoint;

  xhttp.onreadystatechange = function() {
    console.log('readyState: ', this.readyState);
    if (this.readyState === 4) {
      if (this.status === 200) {
          console.log('success!');
      } else {
          console.log('error: ', JSON.stringify(this));
      }
    }  
  };
  xhttp.open(method, url, true);
  xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  if (payload) {
    // 转换后再发送
    const encodedPayload = objectToFormUrlEncoded(payload);
    xhttp.send(encodedPayload);
  } else {
    xhttp.send();
  }
}

后端配置确认(Express框架为例)

确保后端已经配置了解析application/x-www-form-urlencoded请求体的中间件,否则即使前端格式正确,后端也无法读取数据:

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

// 解析url编码的请求体,必须配置
app.use(express.urlencoded({ extended: true }));

// 之后在路由中即可通过req.body获取数据
router.post('/signin', (req, res, next) => {
    console.log('用户名:', req.body.username);
    console.log('密码:', req.body.password);
    // 其他逻辑...
});

可选方案:改用JSON格式发送

如果更倾向于JSON格式传输数据,可以修改前端的请求头和Payload格式:

function ajax(endpoint, method, payload) {
  const xhttp = new XMLHttpRequest();
  const url = 'http://localhost:3000/' + endpoint;

  xhttp.onreadystatechange = function() {
    // 回调逻辑不变...
  };
  xhttp.open(method, url, true);
  // 修改Content-Type为JSON
  xhttp.setRequestHeader('Content-Type', 'application/json');
  if (payload) {
    // 将对象转为JSON字符串发送
    xhttp.send(JSON.stringify(payload));
  } else {
    xhttp.send();
  }
}

对应的后端需要配置JSON解析中间件:

app.use(express.json());

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 08:23:55