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

使用AJAX从Node.js/MongoDB获取数据渲染HTML页面问题求解

问题修复方案

一、后端接口返回undefined修复

问题根源

getCalendar 方法中使用回调式的Mongoose查询,回调函数内的返回值无法传递到方法外层,且方法本身未返回异步结果,导致调用时拿到的是undefined,await也无法生效。

修复代码

  1. 修改mongo.js的getCalendar方法:
const mongoose = require("mongoose");
const calendarSchema = require("./models/calendario");

const mongouri = "mongodb+srv://***:***@cluster0.joeep.mongodb.net/***";
var connection = mongoose.createConnection(mongouri);
var Calendar = connection.model("Calendario", calendarSchema, "Calendario");

// 改成async方法,直接返回查询结果
exports.getCalendar = async () => {
  try {
    return await Calendar.find();
  } catch (err) {
    throw err;
  }
};
  1. 修改app.js,增加异常处理和静态资源托管(方便前端页面访问):
const express = require("express");
const mymongo = require("./mongo.js");
const path = require("path");

const app = express();
// 托管静态html文件,把noleggi.html放在项目根目录的public文件夹下
app.use(express.static(path.join(__dirname, 'public')))

app.get("/api/calendar", async function (req, res) {
  try {
    const data = await mymongo.getCalendar();
    // 直接返回json格式数据
    res.json(data);
  } catch (err) {
    res.status(500).json({error: err.message})
  }
});

app.listen(3000, () => console.log('服务运行在http://localhost:3000'));

这里建议接口路径改到/api/calendar,和静态页面路径区分开,避免冲突。

二、AJAX success回调不触发修复

问题根源

  1. 没有引入jQuery依赖,$.ajax是jQuery提供的方法,直接调用会报$ is not defined错误,代码直接中断
  2. 请求参数中data: JSON.stringify(data)的data变量未定义,会直接报错
  3. 如果直接双击打开html文件走的是file://协议,和接口的http://localhost:3000不同域,会触发跨域限制,请求失败

修复代码

把noleggi.html放到项目根目录的public文件夹下,内容修改为:

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Calendar</title>
        <!-- 引入jQuery依赖 -->
        <script src="https://cdn.staticfile.org/jquery/3.6.4/jquery.min.js"></script>
    </head>
    <body>
        <div class="main class">
            <h1>CALENDAR</h1>
            <div class="calendar">
            </div>
        </div>
        <script>
            $.ajax({
                type: 'GET',
                // 请求修改后的接口地址
                url: '/api/calendar',
                success: function (data) {
                    alert('请求成功');
                    console.log('拿到的数据:', data);
                },
                // 增加错误回调方便排查问题
                error: function (err) {
                    console.error('请求失败:', err);
                }
            });
        </script>
    </body>
</html>

验证方式

启动服务后访问http://localhost:3000/noleggi.html即可正常触发请求,拿到数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 02:54:05