首页 > 解决方案 > 无法显示来自 MongoDB 的内容,给了我空数组 []

问题描述

我试图显示一个数组,即来自 MongoDB 的列表,找不到我犯错的地方,因为当我转到http://localhost:4000时,这是我让我的服务器启动的地方,它给出了一个空 [ ]。另外我使用了核心中间件,因为我将后端和前端分开,所以我的前端可以随时访问我的后端。我的 UI 是用 React 制作的。后端使用 NodeJS。

这是我的后台

const express = require("express");
const mongoose = require("mongoose");
const app = express();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

const bodyParser = require("body-parser");

app.use(bodyParser.json());

mongoose
  .connect("mongodb://localhost:27017/infos")
  .then(() => console.log("Connected to MongoDB..."))
  .catch(err => console.error("Could not connect to MongoDB"));

const Infos = mongoose.model(
  "infos",
  new mongoose.Schema({
    name: {
      type: String,
      required: true
    },
    email: {
      type: String,
      required: true
    },
    phone: {
      type: String,
      required: true
    }
  })
);

let router = express.Router();

router.get("/infos", (req, res) => {
  Infos.find((err, result) => {
    console.log(err);
    console.log(result);
    res.send(result);
  });
});

app.use(router);

const Port = process.env.PORT || 4000;

app.listen(Port, () =>
  console.log(`Server started at http://localhost:${Port}`)
);

module.exports = Infos;

这是我的前端

import React, { Component } from "react";
import axios from "axios";

class Infos extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: []
    };
  }

  render() {
    return (
      <React.Fragment>
        <div className="container">
          <div className="row">
            {this.state.items.map(el => {
              return (
                <div className="col">
                  <div>
                    <h3>{el.name}</h3>
                    <h3>{el.email}</h3>
                    <h3>{el.phone}</h3>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </React.Fragment>
    );
  }

  componentDidMount() {
    axios.get("http://localhost:4000/infos").then(res => {
      this.setState({
        items: res.data
      });
    });
  }
}

export default Infos;

标签: javascripthtmlnode.jsreactjsmongodb

解决方案


我还在 MongoDB 中使用姓名、电子邮件和电话创建了“信息”数据库。


推荐阅读