Home > database >  How to fetch data and make a route with the same endpoint React
How to fetch data and make a route with the same endpoint React

Time:02-08

I have an endpoint from where i retrieve data,it is /community.
My react app use 3001 port but the node server where is the /community endpoint use 3000 port,the problem is that when i'm trying to route to localhost:3001/community to display a component,it gives me the json data from the server,but i need to display the component,could you help me to identify and fix the problem please?
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  

And users.js where i fetch data:

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)
      })
  }
}

CodePudding user response:

A common pattern is to prefix all your proxied URLs with /api or similar.

For example

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

This will proxy any request starting with /api to your Node server endpoints, removing the /api prefix, ie

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

Then make your requests to /api-prefixed URLs

axios.get("/api/community")

You can make this even easier by configuring an Axios instance with the appropriate baseURL

const api = axios.create({
  baseURL: "/api"
})

api.post("/subscribe")
api.post("/unsubscribe")
api.get("/community")
  •  Tags:  
  • Related