如何使用 React 从猫鼬读取 api



我正在尝试从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);

通常我们使用 componentDidMount 从 apis 获取数据。 调用以获取数据的最佳位置是在 componentDidMount(( 中。componentDidMount(( 只在客户端上调用一次,而 componentWillMount(( 被调用两次,一次在服务器上,一次在客户端。它在客户端从服务器接收数据时在初始呈现之后以及数据显示在浏览器中之前调用。

最新更新