【发布时间】:2021-06-06 12:15:51
【问题描述】:
所以,我需要将数据从 express 作为后端发送到 react.js 作为前端我不知道我是否使用了正确的方法
所以我想做的是,当我在 mywebsite.com/home 时,我会从数据库中获取所有帖子 这将是用户名和他的帖子......但我在这里得到的是我在 mywebsite.com 它显示来自 /api 的数据并快速更改来自 /s 的数据
import React, { useEffect } from 'react';
import "./App.css";
import logo from './logo.svg';
import './App.css';
const App = () => {
const {user, body} = useFetchData();
return (
<div>
<label className='username'> user is here {user}</label>
<br></br>
<label className='body'>body is here {body}</label>
</div>
);
};
function useFetchData() {
const [data, setData] = React.useState({});
useEffect(() => {
fetch('/api')
.then(res => res.json())
.then(setData);
}, []);
useEffect(() => {
fetch('/s')
.then(res => res.json())
.then(setData);
}, []);
return data;
}
export default App;
后端
// server/index.js
const path = require('path');
const express = require("express");
const PORT = process.env.PORT || 3001;
const app = express();
app.use(express.static(path.resolve(__dirname, '../facebook-clone/build')));
// Handle GET requests to /api route
app.get("/api", (req, res) => {
res.json({
user: "zeyad alaa",
body: "this is body 1"
});
});
app.get("/s", (req, res) => {
res.json({ user: "zeyad ",
body: "this is body 2" });
});
// All other GET requests not handled before will return our React app
// app.get('*', (req, res) => {
// res.sendFile(path.resolve(__dirname, '../facebook-clone/build', 'error.html'));
// console.log("s3");
// });
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});
知道为什么要这样做吗? 为什么它不等我进入 mywebsite.com/home ?
我知道我在这里遗漏了很多东西,但你能帮我了解这些概念吗?
【问题讨论】: