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

Node.js服务器中Ajax POST请求404,GET请求正常问题排查

Fixing the 404 Error When POSTing Updated JSON Data to Your Node.js Server

Hey there, let's break down what's causing that 404 and get your data sync working properly!

The core issue here is that you're trying to send a POST request directly to a static JSON file path. Node.js (and frameworks like Express) only handle GET requests for static files via middleware like express.static—it has no built-in logic to process POST requests to static file locations, hence the 404 error. To sync your frontend changes to the server file, you need to create a dedicated POST route to handle the data write operation.

Step 1: Update Your Backend Code

First, let's adjust your backend to add a proper route for saving data, plus essential middleware to parse JSON requests:

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

// Serve static files from your public directory (required for frontend access)
app.use(express.static('public'));
// Parse JSON request bodies so we can read data sent from the frontend
app.use(express.json());

// Your existing root route
app.get('/', function (req, res) {
  res.render('index');
});

// NEW: Add a POST route to handle saving updated data
app.post('/save-updated-requests', (req, res) => {
  try {
    // Get the modified data sent from the frontend
    const updatedData = req.body;
    // Define the full path to your target JSON file (avoids relative path issues)
    const targetFile = path.join(__dirname, 'public/assets/frontEndJSON/allrequests.json');
    
    // Write the updated data to the file
    fs.writeFileSync(targetFile, JSON.stringify(updatedData, null, 2));
    
    // Send a success response back to the frontend
    res.status(200).json({ message: 'Data saved successfully!' });
  } catch (err) {
    // Handle any errors during file write
    console.error('Error saving data:', err);
    res.status(500).json({ error: 'Failed to save data to server' });
  }
});

// Start your server (adjust port as needed)
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

Note: Your existing code that merges multiple JSON files into allrequests.json can stay—you can run that logic once on server startup, or turn it into a separate endpoint if you need to refresh the merged data periodically.

Step 2: Adjust Your Frontend Ajax Request

Now update your frontend to send the POST request to the new route, not directly to the JSON file. Also, add a contentType header to ensure the server recognizes the JSON data:

var back = JSON.stringify(q.items, null, 2);
$.ajax({
  type: 'POST',
  url: '/save-updated-requests', // Point to our new backend route
  data: back,
  contentType: 'application/json', // Critical: tells server we're sending JSON
  dataType: 'json',
  success: function(response) {
    console.log(response.message);
    // Add success UI feedback here (e.g., a toast message or page refresh)
  },
  error: function(xhr, status, err) {
    console.error('Save failed:', err);
    // Add error handling UI here
  }
});

Why This Works

  • Static file middleware only handles GET requests for reading assets—POST requests need custom routing to handle business logic like writing files.
  • The express.json() middleware parses the JSON data sent from the frontend so your backend can access it via req.body.
  • The dedicated POST route takes the modified data and writes it directly to your target JSON file, syncing the frontend changes to the server.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:20:58