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

如何通过AJAX发送表单数据并在Node.js中读取

Node.js Server Code to Handle Your AJAX POST Request

Based on your provided jQuery AJAX code, here's a complete Node.js implementation (using Express.js, the most common framework for such APIs) to receive and process the POST request:

Step 1: Setup Your Project

First, create a new project directory and initialize it:

mkdir ajax-form-handler && cd ajax-form-handler
npm init -y
npm install express

Step 2: Server Code (server.js)

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

// Middleware to parse URL-encoded form data (matches jQuery's default AJAX content type)
app.use(express.urlencoded({ extended: true }));

// POST endpoint to handle your form submission
app.post('/submit', (req, res) => {
  try {
    // Extract the stringified form data from the request body
    const formDataString = req.body.formData;
    // Parse the string into a usable JavaScript object
    const formData = JSON.parse(formDataString);

    // --------------------------
    // Add your custom processing logic here
    // e.g., validate data, save to a database, run calculations, etc.
    console.log('Received form data:', formData);
    // --------------------------

    // Send a JSON response back to the client
    res.json({
      status: 'success',
      message: 'Form data processed successfully',
      receivedData: formData
    });
  } catch (error) {
    // Handle errors like invalid JSON formatting
    console.error('Error processing request:', error);
    res.status(400).json({
      status: 'error',
      message: 'Failed to process form data. Invalid JSON received.'
    });
  }
});

// Start the server
app.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}`);
});

Key Details to Note:

  • Middleware Selection: We use express.urlencoded() because your jQuery AJAX call sends data in application/x-www-form-urlencoded format by default (you didn't specify contentType: 'application/json'). If you wanted to send raw JSON directly from the client, you'd update the AJAX call to set that contentType and use express.json() middleware here instead.
  • JSON Parsing: Your client code stringifies the form data before sending it, so we need to parse it back into a JavaScript object to work with the data effectively.
  • Error Handling: The try/catch block ensures the server doesn't crash if invalid JSON is sent, and returns a clear error response to the client.
  • Response Format: The server sends a JSON response, which aligns with the dataType: "json" setting in your AJAX request—this guarantees the client's success handler receives the data correctly.

To start the server, run:

node server.js

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:27:37