【发布时间】:2020-04-16 01:45:55
【问题描述】:
我正在尝试从 mongodb 读取我的 rest api 中的数据。但是,我无法对从中读取数据做出反应。这是我的代码。我可以从其他 API 中提取,但不能从我的自定义中提取。我试过更改 json.data 但没有用。
import React from "react";
const url = "http://localhost:27017/projects";
export default class list extends React.Component {
constructor(props) {
super(props);
this.state = {
projects: []
};
}
fetchData() {
fetch(url)
.then(res => res.json())
.then(json => this.setState({ projects: json.data }));
}
componentWillMount() {
this.fetchData();
}
render() {
return (
<div>
<h1 style={{ fontWeight: "1" }}>Project List</h1>
<ul>
{this.state.projects.map(s => (
<li>{s.sId}</li>
))}
</ul>
</div>
);
}
}
我认为我的 api 设置方式也存在问题。请看一下。是的,我可以通过我的邮递员获取 api。
var app = require("express")();
var mongoose = require("mongoose");
var bodyParser = require("body-parser");
app.use(bodyParser.json());
//create a connection to database
mongoose.connect("THE URL HERE");
//define a "table" structure
var ProjectSchema = new mongoose.Schema({
sId: String,
sName: String,
sYear: String,
cId: String,
cName: String,
sem: String,
aName: String,
aDes: String,
aPer: String,
tech: String,
scope: String,
des: String,
company: String,
app: String,
photoURL: String
});
var Project = mongoose.model("Project", ProjectSchema);
app.get("/projects", function(req, res) {
Project.find({}, function(err, projects) {
res.send(projects);
});
});
app.post("/projects", function(req, res) {
Project.create(req.body, function(err, project) {
res.send(project);
});
});
app.delete("/projects/:id", function(req, res) {
Project.deleteOne({ sId: req.params.id }, function(err, result) {
res.send(result);
});
});
app.put("/projects/", function(req, res) {
Project.findOneAndUpdate(
{ sId: req.body.sId },
{ sName: req.body.sName },
function(err, result) {
res.send(result);
}
);
});
app.get("/projects/search/:keyword", function(req, res) {
Project.find({ sId: req.params.keyword }, function(err, result) {
res.send(result);
});
});
app.listen(27017);
【问题讨论】:
标签: reactjs api express mongoose