【问题标题】:Axio's request gets an empty response from Node.jsAxio 的请求得到 Node.js 的空响应
【发布时间】: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 &amp;&amp; data.map((person) =&gt; 应该是!loading &amp;&amp; data.map((person) =&gt; 。一旦它没有加载并且有数据,你就不会渲染任何东西。
  • 或者你根本不需要loading 条件——如果加载是true,你已经返回。
  • @tromgy 好的,删除了loading。 @Jb31 该死的不,有空大括号 {} 因为我怀疑是解析器问题?

标签: node.js reactjs mongodb


【解决方案1】:

知道了 问题出在 Promise 对象上,需要稍作修改。我发布解决方案:

app.get('/', (req, res) => {
 // console.log(`${req.method} ${req.url}`);
  const entries = Person.find().exec();
  entries.then((result) => {
    res.json(result);
  }).catch((error) => {
    console.log(error);
  })
});

then() 需要两个参数 (result) 回调和 catch() 错误。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-05
    • 2020-02-08
    • 1970-01-01
    • 2017-05-06
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    相关资源
    最近更新 更多