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

如何用纯JavaScript替代jQuery向Express后端发送POST请求?

从jQuery POST转为纯JavaScript实现(基于Fetch API)

场景回顾

很高兴看到你已经通过Fetch API找到了解决方向!你首次尝试用Express搭建轻量级后端,希望从前端HTML/JS发送POST请求,已经有了jQuery版本的实现,现在想要切换到纯JavaScript方案,下面我帮你把整个流程梳理清楚,确保代码和你的后端完美配合。

你的现有代码

服务端Express代码

var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("public"));
const greens = {"orange"}
app.get("/greens", (req, res) => {
 res.json(greens);
});
app.post('/greens', (req,res) => {
 var itemName=req.body.itemName;
 console.log("name = "+itemName);
 res.end("yes");
});
app.listen(3000, "localhost", () => {
 console.log("the server is up and running! http://localhost:3000/greens");
});

jQuery版本前端代码

$(document).ready(function(){
 var itemName;
 $("#submit").click(function() {
 let Name = "banana";
 $.post("http://localhost:3000/login",{itemName: Name}, function(data){
 });
 });
});

注:你的后端POST接口是/greens,但jQuery代码里写的是/login,这里应该是笔误,下面的纯JS实现会统一对接/greens接口。

纯JavaScript(Fetch API)完整实现方案

结合你的HTML按钮,把Fetch API和前端交互逻辑整合起来,完整代码如下:

// 等待DOM完全加载后执行逻辑
document.addEventListener('DOMContentLoaded', function() {
  // 获取页面上的submit按钮
  const submitBtn = document.getElementById('submit');
  
  // 给按钮绑定点击事件
  submitBtn.addEventListener('click', function() {
    const itemName = "banana"; // 你要发送的目标数据
    fetch("http://localhost:3000/greens", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ itemName: itemName })
    })
    .then(response => response.text()) // 后端返回的是纯文本"yes",用text()解析
    .then(data => {
      console.log('后端返回结果:', data); // 可以在这里处理返回的响应内容
    })
    .catch(error => {
      console.error('请求出现异常:', error); // 捕获请求过程中的错误
    });
  });
});

关键细节说明

  • DOM加载监听:用document.addEventListener('DOMContentLoaded', ...)替代jQuery的$(document).ready(),确保页面元素加载完成后再绑定事件,避免找不到按钮的问题。
  • 请求头配置:因为后端启用了bodyParser.json()解析JSON数据,所以必须设置Content-Type: application/json,告诉后端我们发送的是JSON格式的请求体。
  • 请求体处理:用JSON.stringify()把JavaScript对象转为JSON字符串,这样后端才能通过req.body.itemName正确读取到数据。
  • 响应解析:后端用res.end("yes")返回纯文本,所以用response.text()解析响应;如果后端返回JSON格式数据,就换成response.json()即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 11:22:48