【发布时间】:2022-02-01 19:30:11
【问题描述】:
我正在开发一个小型演示应用程序,以展示 Gatsby、Node.js 和 MongoDB 如何协同工作,但我无法将 Node.js 应用程序中的数据发送回 Gatsby 前端。我使用标准包,如 axios、mongodb、mongoose 和 express。服务器获取GET 请求并从数据库中获取数据,控制台显示 2 个获取的文档,但它们不会被发送回 React 组件。 Web 检查器显示此错误消息:Failed to load resource: the server responded with a status of 404 (Not Found)。我想我在解析要发送的数据时做错了根据错误。这很奇怪,因为 json 是首选格式。
import React, { useState, useEffect } from "react";
import axios from "axios";
const IndexPage = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect( () => {
setLoading(true);
axios.get("http://192.168.178.84:3001/")
.then((response) => {
setData(response.data);
})
.catch((error) => {
console.error("Error fetching data: ", error);
setError(error);
})
.finally(() => {
setLoading(false);
});
}, []);
if (loading) return "Loading...";
if (error) return "Error!";
return (
<main>
{loading && data.map((person) => (
<li key={person._id}>
{person.first_name}
</li>
))}
</main>
)
}
Node.js
const express = require("express");
const app = express();
const connectDb = require("./config/mongoConnection");
const mongoose = require('mongoose');
const schema = new mongoose.Schema({
first_name: String,
last_name: String
});
const Persons = mongoose.model('persons', schema);
const port = process.env.PORT || 3001;
connectDb();
app.get('/', (req, res) => {
console.log(`${req.method} ${req.url}`);
const entries = Persons.find().exec();
entries.then(res.json(entries));
entries.then(console.log);
})
mongoose.connection.once("open", () => {
console.log("Connected to MongoDB ");
app.listen(port, () => console.log(`listening on port ${port}`));
});
【问题讨论】:
-
当您在浏览器中打开
http://192.168.178.84:3001时,它会显示正确的数据吗? -
这个:
loading && data.map((person) =>应该是!loading && data.map((person) =>。一旦它没有加载并且有数据,你就不会渲染任何东西。 -
或者你根本不需要
loading条件——如果加载是true,你已经返回。 -
@tromgy 好的,删除了
loading。 @Jb31 该死的不,有空大括号{}因为我怀疑是解析器问题?