Search code examples
javascriptreactjsapiserverclient-server

Server side or Clint side API call?


If you're working with React.js, what is the best way to make an API call? For example, if I'm trying to get some book data from google books API should I do this on the client side with React.js or on the server side. Why would it be better to do it on one side vs the other? Thanks.


Solution

  • You can do something like this.

    const express = require('express');
    const app = express();
    const path = require('path');
    const fs = require('fs');
    const proxy = require('http-proxy-middleware');
    
    app.use(
      '/api',
      proxy({
        target: 'http://api.books.com',
        changeOrigin: true,
        ws: true,
        pathRewrite: { '^/api': '' },
      })
    );
    
    const index = fs.readFileSync(path.resolve('./build', 'index.html'), { encoding: 'utf-8' });
    
    app.get('*', (req, res) => {
      res.contentType('text/html').send(index);
    });
    
    const server = app.listen(3000, function() {
      const host = server.address().address;
      const port = server.address().port;
    
      console.log('The server is running at http://%s:%s/', host, port);
    });
    

    And call like this (throw proxy), to not have problems with CORS or to replace server after.

    fetch('/api/get-books')