【问题标题】:Getting data from nodejs/MongoDB in a HTML page with Ajax使用 Ajax 在 HTML 页面中从 nodejs/MongoDB 获取数据
【发布时间】:2021-12-19 15:14:11
【问题描述】:

我正在尝试使用 nodejs/mongoose 从我的 MongoDB 数据库中获取数据,然后我通过 URL (http://localhost:3000/) 发送数据,并且我想在 HTML 页面中获取和管理数据.为了获取数据,我使用 AJAX 在“http://localhost:3000/”发出 GET 请求。我知道使用像 ejs 这样的视图引擎会容易得多,但这是一个大学项目,我必须专门使用 AJAX。我在使用 API 发送数据以及使用 AJAX 检索数据时遇到了一些问题。 这是我的代码。

这是我的集合“Calendario”的模型(名称是意大利语),这个文件名为calendario.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

//schema define the structure of the document
const calendarSchema = new Schema({
  id_macchina: {
    type: String,
    required: true,
  },
  data_inizio: {
    type: Date,
    required: true,
  },
  data_fine: {
    type: Date,
    required: true,
  },
  noleggio: {
    type: Boolean,
    required: false,
  },
  restituzione: {
    type: Boolean,
    required: false,
  },
});

module.exports = calendarSchema;

这是我连接到数据库的文件 mongo.js 并从集合“Calendario”中检索数据(出于显而易见的原因,我在连接字符串中使用“*”,在我的代码中连接字符串是正确的) .我已经检查过了,连接工作正常。此外,如果我在函数内部将“结果”打印到控制台(使用console.log(results);),Calendar.find(function (err, results) {}); 我会得到我正在寻找的 JS 对象格式的数据。所以直到这里,一切似乎都以正确的方式工作。

const mongoose = require("mongoose");
const calendarSchema = require("./models/calendario");

const { MongoClient } = require("mongodb");

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

exports.getCalendar = (req, res) => {
  try {
    Calendar.find(function (err, results) {
      return results;
    });
  } catch (err) {
    return err;
  }
};

这是一个简单的 API 文件 app.js。我认为这是第一个问题,因为如果我尝试打印到控制台,mymongo.getCalendar() 的输出将打印“未定义”。

const express = require("express");
const mymongo = require("./mongo.js");

const app = express();

app.listen(3000);

app.get("/", async function (req, res) {
  res.send(await mymongo.getCalendar());
});

第二个问题出在名为“noleggi.html”的 HTML 文件中。在这里,我使用 AJAX 向地址“http://localhost:3000/”发出 GET 请求。在这段代码中,我什至没有尝试显示数据,因为它没有在成功字段中输入函数。事实上,我在函数中放置了一个警报和一个 console.log(),我在网页上看不到任何东西。这是该文件的代码:

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Calendar</title>
    </head>

    <body>
        <div class="main class">
            <h1>CALENDAR</h1>
            <div class="calendar">
            </div>
        </div>
        <script>
            $.ajax({
                    type: 'GET',
                    data: JSON.stringify(data),
                    url: '/',
                    success: function (data) {
                        alert('test');
                        console.log('test');
                    }
                });
                
        </script>
    </body>
</html>

【问题讨论】:

    标签: node.js ajax mongodb express mongoose


    【解决方案1】:

    getCalendar 不是async 函数。它也不需要任何参数。

    您可以像这样更改代码:

    app.get("/", async function (req, res) {
      try{
        const calendar = await mymongo.getCalendar();
        res.send(calendar);
      } catch(e) {
        //handle reject case
      }
    });
    
    

    mongo.js 像这样:

    exports.getCalendar = () => {
      return new Promise((resolve, reject) => {
        Calendar.find(function (err, results) {
            if(err){
                reject(err);
            }else{
                resolve(results);
            }
        });
      })
    };
    

    【讨论】:

    • 现在可以了,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多