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

Node.js+Express项目中AJAX POST请求报404错误求助

问题:AJAX POST请求返回404但路由存在(Node.js+Express)

项目结构

  • public
    • scripts
      • script.js
  • routes
    • chats.js
  • views
    • chats.ejs
  • index.js

核心代码文件

index.js(端口3000)

//...
const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
require('dotenv').config();

//Express instance
const app = express();
const port = process.env.PORT;

//Mongoose instance
mongoose.connect(process.env.MONGO_URI)
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Could not connect to MongoDB:', err));

//Body-parser instance
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

//Express-session instance
app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
}));

//Static-files instance & EJS 
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');

// Routers
const authenticationRouter = require('./routes/auth');
app.use("/auth", authenticationRouter);

const chatsRouter = require('./routes/chats');
app.use("/chats", chatsRouter);

// Routes
app.get("/", (req, res) => {
    res.render("index");
});

//Express listener
app.listen(port, () => console.log(`Server running on port ${port}.`));

script.js

$(document).ready(function () {
    $('#addFriendForm').on('submit', function (e) {
        e.preventDefault();
        const friendName = $('#friendName').val();
        if (friendName === '') {
            $('#error-message').text('Usuário não encontrado.');
        } else {
            $('#error-message').text('');

            // Send AJAX request to add friend
            $.ajax({
                url: '/chats/addfriend',
                type: "post",
                method: 'POST',
                data: { friendName: friendName },
                success: function (data) {
                    if (data.success) {
                        const avatarUrl = `/path/to/avatars/${friendName}.png`; 
                        $('#friendsList').append(`
                            <li class="list-group-item">
                                <a href="#" class="d-flex align-items-center friend-item" data-friend-name="${friendName}">
                                    <img src="${avatarUrl}" alt="${friendName}" class="friend-avatar me-2">
                                    ${friendName}
                                </a>
                            </li>
                        `);
                        $('#friendName').val('');
                    } else {
                        $('#error-message').text(data.error);
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log('Erro AJAX:', textStatus, errorThrown);
                    $('#error-message').text('Erro ao adicionar amigo. Tente novamente.');
                }
            });
        }
    });
});

控制台错误日志

POST http://localhost:3000/chats/addfriend 404 (Not Found)

chats.js路由代码

router.get('/', async (req, res) => {
    try {
        if (!req.session.userId) {
            return res.redirect("/auth/login");
        }

        const currentUser = await User.findById(req.session.userId);
        
        const friendship = await Friendship.findOne({ user: currentUser._id }).populate('friends');

        const friendsList = friendship ? friendship.friends : [];

        const allUsers = await User.find().select('_id username nickname');

        return res.render('chats', { currentUser, friendsList, allUsers });

    } catch (err) {
        console.error(err);
        res.status(500).send('Erro interno do servidor');
    }
});
router.post('/addfriend', async (req, res) => {
    const { friendName } = req.body;

    try {
        const friend = await User.findOne({ username: friendName });
        if (!friend) {
            console.log('Não foi possível encontrar o usuário pelo nome de usuário', friendName);
            return res.status(404).json({ error: 'Usuário não encontrado.' });
        }

        const currentUser = await User.findById(req.session.userId);

        if (!currentUser || !currentUser.friends) {
            console.log('Não foi possível encontrar o usuário atual ou eles não têm amigos', currentUser);
            return res.status(404).json({ error: 'Usuário não encontrado ou amigos não inicializados.' });
        }

        currentUser.friends.push(friend._id);
        await currentUser.save();

        res.status(200).json({ success: true });

    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Erro ao adicionar amigo. Tente novamente mais tarde.' });
    }
});

问题现象

将/chats/addfriend改为GET方法后,通过浏览器访问能正常返回200,但POST方法通过AJAX请求始终返回404,请求配置看起来无问题。


排查与解决方案

1. 检查chats.js的路由导出

你贴的chats.js代码缺少router的定义与导出语句,这是最可能的原因。Express无法识别未导出的路由,自然会返回404。需确保文件开头和结尾添加以下代码:

const express = require('express');
const router = express.Router();
// ... 你的路由代码 ...
module.exports = router;

2. 清理AJAX请求的冗余参数

你的AJAX配置同时写了type: "post"和method: 'POST',虽jQuery会优先使用method,但冗余可能引发潜在问题,建议只保留一个:

$.ajax({
    url: '/chats/addfriend',
    method: 'POST', // 仅保留该参数
    data: { friendName: friendName },
    // ... 其他配置 ...
});

3. 验证会话与请求参数

在POST路由开头添加日志,确认会话状态与请求参数是否正常接收:

router.post('/addfriend', async (req, res) => {
    console.log('会话userId:', req.session.userId);
    console.log('接收的参数:', req.body);
    // ... 原有代码 ...
});

4. 确认路由挂载顺序

确保app.use("/chats", chatsRouter);的挂载顺序在全局路由之前,你的index.js目前顺序是正确的,但如果有其他路由匹配了/chats/addfriend的POST请求,会导致冲突,可检查是否存在此类情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 14:22:07