【问题标题】:react express. how to fetch mongodb data?反应快递。如何获取 mongodb 数据?
【发布时间】:2021-09-13 13:54:16
【问题描述】:

我不知道如何从反应中获取 express 中的 course2... console.log(course2) 给了我来自 mongodb 的正确数据...

但是我如何在 react 中使用 fetch 来获取这些数据?
我还没有学习 axios 但是如果有人知道如何在 axios 中做到这一点,那没关系....

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, Authorization");
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    next();
});

app.use(express.json()); //Used to parse JSON bodies... post values
app.use(express.urlencoded( {extended: true})); //Parse URL-encoded bodies (html-form)

mongoose.connect("mongodb+srv://-----", 
    { useUnifiedTopology: true, useNewUrlParser: true })
    .then(() => console.log('connected'))
    .catch(err => console.error('no connection', err))

 const sensor1 = new mongoose.Schema({
    temp1: Number,
    hum1:  Number,
    date: { type: Date, default: Date.now },    
})

 const Course = mongoose.model('Course', sensor1)  

var db = mongoose.connection
db.on('error', console.log.bind(console, "connection error")); // för insertOne
db.once('open', function(callback){ 
    console.log("connection succeeded"); 
}) 


async function getCourse() {
   let course2 = await Course.find()
   console.log(course2)
}
app.listen(5000, () => {
    console.log('Listening on port 5000')
})   

getCourse()```

【问题讨论】:

    标签: node.js reactjs mongodb express fetch


    【解决方案1】:

    第 1 步:创建端点

    您首先需要在后端/快速应用中定义一个端点。例如:

    app.get("/courses", async (req, res, next) => {
       try {
          const course2 = await Course.find();
          res.status(200).send(course2);
       } catch (err) {
          console.log(err);
          res.status(500).send();
       }
    });
    

    现在,您有了一个可以从前端代码调用的端点:http://localhost:5000/courses

    第 2 步:使用 Axios 使用 Endpoint

    Axios 非常易于使用。例如:

    import axios from 'axios'
    
    ...
    
    axios.get('http://localhost:5000/courses').then(response => {
         // response.data is your 'course2'
         console.log(response.data)
    }).catch(err => {
         console.log(err);
    });
    

    如果你要在你的 React 应用程序中调用这个新的 api,你可能会将这个 axios 调用放在 componentDidMountuseEffect 或其他一些函数中。

    【讨论】:

      猜你喜欢
      • 2018-07-11
      • 2021-06-17
      • 2022-01-09
      • 2019-11-03
      • 2021-12-02
      • 2021-05-23
      • 2016-08-16
      • 2019-09-29
      • 1970-01-01
      相关资源
      最近更新 更多