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

Node.js+Express+Ajax请求异常:先400后404,求排查解决

Fixing Your Express Ajax POST Issues (400 → 404 Errors)

Hey there! Let's work through your problems step by step—you're really close, just a couple of common missteps with how Express handles routes and middleware.

First: Why the 400 Bad Request?

Your Ajax request sets contentType: "application/json" but sends data: 'TEST'—that's a plain string, not valid JSON. The body-parser.json() middleware expects a properly formatted JSON payload, so it rejects the request with a 400 error when it can't parse the string.

Fix the Ajax Request

Update your post() function to send valid JSON using JSON.stringify():

function post() {
  $.ajax({
    type: "POST",
    url: "/test",
    data: JSON.stringify({ message: "TEST" }), // Wrap data in a JSON object
    contentType: "application/json; charset=utf-8",
    dataType: "json",
  }).done(function (data) {
    console.log("Did it work? " + data.response); // Match the JSON response we'll send
  }).fail(function(xhr, status, error) {
    // Add a fail callback to debug future issues easily
    console.error("Request failed:", error);
  });
}

Second: Why the 404 Not Found?

Here's the big one: In your routes/index.js, you created a brand new Express app instance (var app = express()) and added your POST route to that. But this app is completely separate from the main app defined in app.js—the one that's actually running your server. So your /test route never gets registered with the main application, hence the 404.

Plus, you don't need to reconfigure body-parser in your route file—middleware should be set up in app.js so all routes can use it.

Fix the Route in routes/index.js

Remove the extra app instance and use the existing router to define your POST route:

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index');
});

// Use router.post instead of app.post—this attaches to the main app's router
router.post('/test', function(req, res) {
  console.log("Received request body:", req.body); // Now will log { message: "TEST" }
  // Send a JSON response (matches dataType: "json" in your Ajax request)
  res.json({ response: "hi" });
});

module.exports = router;

Ensure body-parser is Configured in app.js

Double-check that app.js has body-parser set up before registering your routes (this is crucial—middleware runs in order):

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser'); // Import body-parser

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// View engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// Configure body-parser FIRST, before routes
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(express.static(path.join(__dirname, 'public')));

// Register routes AFTER middleware
app.use('/', indexRouter);
app.use('/users', usersRouter);

// ... Rest of your error handling and server setup code

Quick Recap of What We Fixed

  • 400 Error: Fixed by sending valid JSON instead of a plain string in the Ajax request.
  • 404 Error: Fixed by using the existing router (not a new app instance) to define your POST route, so it gets attached to the main server app.
  • Middleware Placement: Moved body-parser configuration to app.js where it belongs, ensuring all routes can access it.

Test your code now—your Ajax POST should work, you'll see the request body logged in your terminal, and the "hi" response will show up in your browser console!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:45:33