完成前後端應用程式後需兩個服務器端口一致才能運行,前端react預設運行的端口port為3000,如果在backend設置的服務器端口port是4000,要解決兩個不同的服務器端口,可以在前端的package.js最上面添加("proxy": "http://localhost:4000 "),設置開發服務器地址。
"proxy":"http://localhost:4000",
"name": "frontend",
"version": "0.1.0",
React 實作
App.js
import {BrowserRouter,Routes ,Route} from 'react-router-dom'
import Home from './Home'
import Nav from './Nav';
function App() {
return (
<div className="App">
<BrowserRouter>
<Nav />
<div className="home">
<Routes>
<Route
path="/"
element={<Home />}
/>
</Routes>
</div>
</BrowserRouter>
</div>
);
}
export default App;
Nav.js
import { Link } from 'react-router-dom'
const Nav = () =>{
return (
<header>
<div className="navber">
<Link to="/">
<h1>Users Information</h1>
</Link>
</div>
</header>
)
}
export default Nav
Home.js
import { useEffect,useState } from "react"
import UserDetails from '../component/UserDetails'
import UserForm from "../component/UserForm"
const Home = () =>{
const [users,setUsers] = useState(null)
useEffect(()=>{
const fetchUsers = async () =>{
const response = await fetch('/api/users')
const json = await response.json()
if (response. success){
setUsers(json)
}
}
fetchUsers()
},[])
return (
<div className="container">
<div className="users">
{users && users.map(user)=>(
<UserDetails key={user._id} user={user} />
))}
</div>
<UserForm />
</div>
)
}
export default Home
UserDetails.js
const UserDetails = ({user})=>{
return(
<div className="user">
<h4>name:{usert.title}</h4>
<p>Load: {user.load}</p>
</div>
)
}
export default UserDetails
UserForm.js
import { useState } from "react"
const UserForm = () => {
const [title, setTitle] = useState('')
const [load, setLoad] = useState('')
const [error, setError] = useState(null)
const handleSubmit = async (e) => {
e.preventDefault()
const user = {title, load }
const response = await fetch('/api/users', {
method: 'POST',
body: JSON.stringify(user),
headers: {
'Content-Type':'application/json'
}
})
const json = await response.json()
if (!response. success){
setError(json.error)
}
if (response. success){
setError(null)
setTitle('')
setLoad('')
}
}
return(
<form className="add" onSubmit={handleSubmit}>
<h3>Add a New User</h3>
<label>User name:</label>
<input
type="text"
onChange={(e)=>setTitle(e.target.value)}
value={title}
/>
<label>Load:</label>
<input
type="number"
onChange={(e)=>setLoad(e.target.value)}
value={load}
/>
<button>Add User</button>
{error && <div className="error">{error}</div>}
</form>
)
}
export default UserForm