skip to Main Content

I’ve got an React app, which calls internally: /api/* actions. In my case these actions are satisfied by NginX which loads relevant back-end code and returns JSON response.

I would like this React app to be "self-served", I would like to implement API back-end: /api/* using JS, so the code runs in the browser.

My app uses: react-router

<BrowserRouter>
    <Switch>
        <Route path={"/users/:path*"} component={UsersPage} />
        <Route path={"/api/:action*"} component={ApiComponent} /> // Return RAW Json here, is it possible?
        <Route component={NotFoundPage} />
    </Switch>
</BrowserRouter>

Is it possible somehow to resolve the /api/*, so I can implement it in my ApiComponent and return raw JSON?

I’ve also experimented with Express JS:

app.group("/api", (router) => {

    router.get("/action", (req, res) => {
        // Implement API action here
    });

});

app.use('/public', express.static('public')) // This allows assets to be loaded from filesystem

app.get("*", (req, res) => {
    res.sendfile('./index.html'); // This loads React app
});

which worked very well, but now I’ve ended up with a problem, how to run this Express JS / NodeJS, in a browser context.

In other words, my question is what are the ways to implement API on the front-end, provide to to existing React app, and run it all in browser.

2

Answers


  1. It’s impossible for React elements to return raw JSON because all React elements return a special object.

    Maybe, you should just set a proxy in your webpack/vite config to point all /api requests to your node server.

    Login or Signup to reply.
  2. If you are using an HTTP client library like Axios, you can use an interceptor, which is a function that gets called for every single HTTP request made and the response received by your application in the browser itself.

    axios interceptor

    Here is the sample code,

    // Add a request interceptor
    axios.interceptors.request.use(function (request) {
        // Do something before request is sent
        request.headers.Authorization = 'Bearer <token>';
        return request;
      }, function (error) {
        // Do something with request error
        return Promise.reject(error);
      });
    
    // Add a response interceptor
    axios.interceptors.response.use(function (response) {
        // Do something with response data
        if (response.status === 401) {
            window.location = '/login';
        }    
        return response;
      }, function (error) {    
        // Do something with response error
        return Promise.reject(error);
      });
    

    Another way is to register a service worker, which essentially acts as a proxy server and can intercept all HTTP requests.

    Also, you can use browser extension like https://github.com/kzahel/web-server-chrome which creates a Web Server for Chrome, serves web pages from a local folder over the network, using HTTP. Runs offline.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search