【问题标题】:Way to display MongoDB data on home page在主页上显示 MongoDB 数据的方式
【发布时间】:2020-02-16 22:23:49
【问题描述】:

我有 MongoDB 数据库,我想在我的网站前端显示。我正在使用快递。每个数据都有类别。我想根据该类别显示数据。如果这种方式太基本的问题,请原谅。我是初学者。有关此的任何想法都会非常有帮助。在此先感谢。

【问题讨论】:

  • 向我们展示您迄今为止的尝试?

标签: node.js angular mongodb express


【解决方案1】:

横幅

要在 Angular(或任何前端)应用程序中查看来自 mongodb 的数据,您必须设置中间件。我看到您正在寻找 nodejs,表示解决方案。我会使用 mongoose 作为 nodejs 应用程序和 mongodb 之间的连接器。要使用猫鼬,我会执行以下操作

const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
const router = express.Router();

    mongoose
      .connect(
        "<Your DB Cnnnection>?retryWrites=true&w=majority",
        { useNewUrlParser: true, useUnifiedTopology: true }
      )
      .then(() => console.log("connected to mongo db"))
      .catch(() => console.log("connection failed")); // Now you are connected with mongo db

//Initial setup
app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET" // Add other verbs you want to support
  );
  next();
});
router.get("", (req, res, next) => {
  const categoryQuery = Category.find(); //Create a category mongoose [model](https://mongoosejs.com/docs/guide.html)
  categoryQuery
    .find()
    .then(data => {
      res.status(200).json({
        message: "<Category> data fetched successfully",
        data: data,
      });
    });
});
// Setup route
app.use("/api/<category>", router);

现在您可以运行此 JS 文件来为后端应用程序提供服务。因为我已经启用了 CORS,您可以直接在前端使用 Angular HttpClient 来获取存储在 mongodb 中并由上述中间件应用程序提供的数据。

【讨论】:

    猜你喜欢
    • 2023-01-15
    • 2023-04-03
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多