如何获取数据并创建具有相同端点的路由React



我有一个从中检索数据的端点,它是/community
我的react应用程序使用3001端口,但/community端点所在的节点服务器使用3000端口,问题是当我试图路由到localhost:3001/community以显示组件时,它会给我来自服务器的JSON数据,但我需要显示组件,你能帮我识别并解决问题吗?

setupProxy.js

const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
createProxyMiddleware('/subscribe', {
target: 'http://localhost:3000',
changeOrigin: true,
headers: {
Connection: "keep-alive"
}
})
);
app.use(
createProxyMiddleware('/unsubscribe', {
target: 'http://localhost:3000',
changeOrigin: true,
headers: {
Connection: "keep-alive"
}
})
);
app.use(
createProxyMiddleware('/community', {
target: 'http://localhost:3000',
changeOrigin: true,
headers: {
Connection: "keep-alive"
}
})
);
} 

App.js

import './App.css';
// import JoinUsSection from './components/JoinUsSection';
// import BigCommunitySection from './components/BigCommunitySection';
import { Provider } from 'react-redux';
import { store, persistor } from './store';
import { PersistGate } from 'redux-persist/integration/react'
import { fetchUsers } from './asyncActions/users';
import {Routes,Route} from 'react-router-dom'
import Main from './pages/Main'
import Community from'./pages/Community'
store.dispatch(fetchUsers())
function App() {
return (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<Routes>

{/* <main id='app-container'>
<BigCommunitySection />
<JoinUsSection />
</main> */}

<Route path="/" element={<Main/>}/>
<Route path="/community" element={<Community/>}/>
</Routes>
</PersistGate>
</Provider>
);
}
export default App;

Community.js

import BigCommunitySection from '../components/BigCommunitySection';
const Community = () =>{
return(
<BigCommunitySection/>
)
}
export default Community 

以及users.js获取数据的位置:

import axios from "axios"
import { addUsers } from "../store/usersReducer"
export const fetchUsers = () => {
return dispatch => {
axios
.get('/community')
.then(response => {
dispatch(addUsers(response.data))
})
.catch(error => {
console.log(error)
})
}
}

一种常见的模式是在所有代理URL前面加上/api或类似的前缀。

例如

module.exports = function (app) {
app.use("/api", createProxyMiddleware({
target: 'http://localhost:3000',
pathRewrite: {
"^/api": "" // remove the /api prefix
},
changeOrigin: true,
headers: {
Connection: "keep-alive"
}
})
)
}

这将把以/api开始的任何请求代理到节点服务器端点,删除/api前缀,即

  • /api/subscribe => http://localhost:3000/subscribe
  • /api/unsubscribe => http://localhost:3000/unsubscribe
  • /api/community => http://localhost:3000/community

然后向前缀为/api的URL 发出请求

axios.get("/api/community")

您可以通过使用适当的baseURL配置Axios实例来简化此操作

const api = axios.create({
baseURL: "/api"
})
api.post("/subscribe")
api.post("/unsubscribe")
api.get("/community")