我试图显示一个数组,这是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;
答案 0 :(得分:0)
我还用名称,电子邮件和电话在MongoDB中创建了“信息”数据库。