最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

获得白屏 react.js 但在后端获得输出

网站源码admin35浏览0评论

获得白屏 react.js 但在后端获得输出

获得白屏 react.js 但在后端获得输出

我在 react.js 中出现白屏,但没有反应就得到输出, 这是后端代码 主.js

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const data = require('./sample_data.json');

const app = express();

// Connect to MongoDB
mongoose.connect('mongodb://127.0.0.1:27017/sample_database', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

// Define schema for users
const userSchema = new mongoose.Schema({
  first_name: String,
  last_name: String,
  email: String,
  gender: String,
  phone_price: String,
  car: String,
  income: String,
  city: String,
});

// Create model for users
const User = mongoose.model('User', userSchema);

// Insert sample data into database
User.insertMany(data.users);

// Set up middleware for parsing JSON data in request body
app.use(bodyParser.json());



// Define routes for API
app.get('/api/users', async (req, res) => {
  try {
    // Query database for users that have income lower than $5 USD and have a car of brand “BMW” or “Mercedes”
    const users1 = await User.find({
      car:"BMW" || "Mercedes",
     income: { $lte: 5},
      
    });
    

    // Query database for male users which have phone price greater than 10,000
    const users2 = await User.find({
      gender: 'Male',
      phone_price: { $gt: 10000 },
    });

    // Query database for users whose last name starts with “M” and has a quote character length greater than 15 and email includes his/her last name
    const users3 = await User.find({
      last_name: /^M/,
      $where: `this.email.includes('${this.last_name}') && this.quote.length > 15`,
    });

    // Query database for users which have a car of brand “BMW”, “Mercedes” or “Audi” and whose email does not include any digit
    const users4 = await User.find({
      car: { $in: ['BMW', 'Mercedes', 'Audi'] },
      email: { $not: /\d/ },
    });

    // Query database for top 10 cities which have the highest number of users and their average income
    const cityStats = await User.aggregate([
      { $group: { _id: '$city', count: { $sum: 1 }, income: { $avg: '$income' } } },
      { $sort: { count: -1 } },
      { $limit: 10 },
    ]);

    res.json({
      users1,
      users2,
      users3,
      users4,
      cityStats,
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
});






// Start server
app.listen(5000, () => {
  console.log('Server started on port 5000');
});

前端代码为App.js

import React, { useEffect, useState } from 'react';
import axios from 'axios';

const App = () => {
  const [users1, setUsers1] = useState([]);
  const [users2, setUsers2] = useState([]);
  const [users3, setUsers3] = useState([]);
  const [users4, setUsers4] = useState([]);
  const [cityStats, setCityStats] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('http://localhost:5000/api/users');
        setUsers1(response.data.users1);
        setUsers2(response.data.users2);
        setUsers3(response.data.users3);
        setUsers4(response.data.users4);
        setCityStats(response.data.cityStats);
      } catch (error) {
        console.error(error);
      }
    };
    fetchData(); 
  },[]);
    
  

  const renderUserTable = (users) => {
    if (users.length === 0) {
      return <p>No users found</p>;
    }

    return (
      <table>
        <thead>
          <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email</th>
            <th>Gender</th>
            <th>Phone Price</th>
            <th>Car</th>
            <th>Income</th>
            <th>City</th>
          </tr>
        </thead>
        <tbody>
          {users.map((user) => (
            <tr key={user._id}>
              <td>{user.first_name}</td>
              <td>{user.last_name}</td>
              <td>{user.email}</td>
              <td>{user.gender}</td>
              <td>{user.phone_price}</td>
              <td>{user.car}</td>
              <td>{user.income}</td>
              <td>{user.city}</td>
            </tr>
          ))}
        </tbody>
      </table>
    );
  };

  const renderCityStatsTable = () => {
    if (cityStats.length === 0) {
      return <p>No city stats found</p>;
    }

    return (
      <table>
        <thead>
          <tr>
            <th>City</th>
            <th>Number of Users</th>
            <th>Average Income</th>
          </tr>
        </thead>
        <tbody>
          {cityStats.map((city) => (
            <tr key={city._id}>
              <td>{city._id}</td>
              <td>{city.count}</td>
              <td>{city.income}</td>
            </tr>
          ))}
        </tbody>
      </table>
    );
  };

  return (
    <div>
      <h2>Users which have income lower than $5 USD and have a car of brand “BMW” or “Mercedes”</h2>
      {renderUserTable(users1)}

      <h2>Male Users which have phone price greater than 10,000</h2>
      {renderUserTable(users2)}

      <h2>Users whose last name starts with “M” and has a quote character length greater than 15 and email includes his/her last name</h2>
      {renderUserTable(users3)}

      <h2>Users which have a car of brand “BMW”, “Mercedes” or “Audi” and whose email does not include any digit</h2>
      {renderUserTable(users4)}

      <h2>Top 10 cities which have the highest number of users and their average income</h2>
      {renderCityStatsTable()}
    </div>
  );
};

export default App;

我正在使用 express.js、node.js 使用 REST-api 从 mongodb 检索数据,我在后端获得了所需的输出 我认为他们在渲染数据时反应有问题, 请帮帮我

我已经卸载 npm 包并重新安装它,只在后端获得输出

回答如下:
发布评论

评论列表(0)

  1. 暂无评论