我正在构建一个反应应用程序,在其中将数据播种到 mongoDB 数据库,然后再次从该数据库中获取该数据并将数据呈现给 UI。在本例中,在 Paintings.js 组件中。但是,当对此组件进行更改时,将激活热加载,并显示一个微调器,但几秒钟后,数据在 UI 中不再可见。仅在手动刷新页面时。有时会出现此错误:
“代理错误:无法将请求/绘画从 localhost:3000 代理到 http://localhost:5000/”
我正在运行 react 17.0.2,脚本 4.0.3
我重新安装了 create-react-app ,全局安装nodemon,去掉axios get请求中的正斜杠,在.env文件中添加FAST_REFRESH=false,没有结果。
谢谢你。
server.js 文件
const express = require('express');
const app = express();
const cors = require('cors');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const colors = require('colors')
const products = require('./ProductsDB')
const Product = require('./models/paintingsModel')
app.use(cors());
app.use(express.json())
dotenv.config()
// Connect to mongoDB
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.REACT_APP_URL)
console.log(`MongoDB Connected: ${conn.connection.host}`.brightMagenta)
} catch (error) {
console.error(`Error: ${error.message}`.red.bold)
process.exit(1)
}
}
connectDB()
app.get('/', (req, res, next) => {
res.send('API is running...')
})
//Add data to database
const addDataToCollection = async () => {
try {
await Product.deleteMany()
await Product.insertMany(products, function (err, res) {
console.log('Data imported!'.green.inverse)
console.log("Number of documents inserted: " + res.length);
})
} catch (error) {
console.log(error)
}
}
addDataToCollection()
app.use('/', require('./routes/paintingsRoute'))
app.listen(process.env.REACT_APP_PORT, function () {
console.log(`Express server running in ${process.env.NODE_ENV} on port ${process.env.REACT_APP_PORT}`.yellow)
})
包.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node backend/server",
"client": "cd frontend && npm start",
"dev": "concurrently \"nodemon backend/server\" \"npm run client\""
},
绘画.js
import React, { useState, useEffect, useCallback } from 'react'
import './styles.css'
import axios from 'axios'
//import Loader from './Loader'
const Products = () => {
const [paintings, setPaintings] = useState([])
const [loader, setLoader] = useState(true)
const fetchData = useCallback(async () => {
setLoader(true)
try {
await axios.get('paintings').then(res => {
const data = res.data
setPaintings(data)
setLoader(false)
})
} catch (error) {
console.log(error)
setLoader(true)
}
}, [])
useEffect(() => {
fetchData();
return function cleanup() {
fetchData()
};
}, [fetchData])
return (
<div className="paintingsContainer">
{paintings.map(painting => {
const { name, price, _id, imgSrc, artNr } = painting
return (
<div className="products" key={_id}>
<div className="productName">{name}</div>
<div className="price">Price: ${price}</div>
<div className="imageBox">
{!loader ? <img src={process.env.PUBLIC_URL + `${imgSrc}`} alt="item" className="image" /> :
<div className="loaderPng">
<img src={process.env.PUBLIC_URL + '/img/loader.gif'} alt="spinner" className="spinner" style={{ width: "100px" }} />
</div>}
</div>
<div className="footers cart">Add to cart</div>
<div className="footers buy">Buy this product</div>
<div className="footers art">art-nr:{artNr}</div>
</div>
)
})}
</div>
)
}
export default Products