【问题标题】:How to read api from mongoose using React如何使用 React 从 mongoose 读取 api
【发布时间】: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


    【解决方案1】:

    通常我们使用 componentDidMount 从 api 获取数据。 调用获取数据的最佳位置是在 componentDidMount() 中。 componentDidMount() 在客户端只被调用一次,而 componentWillMount() 被调用两次,一次到服务器,一次在客户端。它在客户端从服务器接收到数据并在数据显示在浏览器中之前进行初始渲染之后调用。

    【讨论】:

      猜你喜欢
      • 2021-09-09
      • 2021-10-13
      • 1970-01-01
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-06
      • 2016-10-17
      相关资源
      最近更新 更多