How can I get rid of a URL in a fetch (to use kind of a variable instead)?

Viewed 749

I have this function for submitting code (see gist https://gist.github.com/constantinscum/4ed753dcd681b4758a8500e4b53d925c) and I don't want to write that //https: in every source file. I was thinking about a global variable but it might be a more elegant solution for this. Do you have any idea how to do that? I want to get rid of the localhost domain URL because it will change after the app will be deployed on a server. Thank you!

3 Answers

Probably this will not give a direct answer to your question, but its a good practice,

What we normally do is create a separate file for api details

for ex:

api.js

  //REACT_APP_SERVER_URL is a env variable in .env file
  const rootUri = process.env.REACT_APP_SERVER_URL
    ? process.env.REACT_APP_SERVER_URL
    : 'http://localhost:3001';

  const apiVersion = 'v1';
  const apiBasePath = `${rootUri}/api/${apiVersion}`; //this is the base path

  export const userApis = {
    all: {
      url: `${apiBasePath}/users`,
      method: 'GET',
    },
    update: {
      url: `${apiBasePath}/user`,
      method: 'POST',
    },
  };

this is how we use it

const fetchAllUser = () => {
    const api = userApis.all;
    fetch(api.url, {
        method: api.url.method,
        body: JSON.stringify(request)
    }...

You should use a proxy to the backend api url, this will allow you to just write the api url without adding server name / domaine

in development you can create setupProxy.js and use http-proxy-middleware to redirect all api calls to the server

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = app => {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:3001',
      changeOrigin: true,
    }),
  );
};

and your fetch call will look something like this

 fetch('/api/code/add')

you can read more about setup proxy Here

and for production it will depend on the tools you will use, (Nginx, Node, ...)

You can make the request without the http://localhost:3000 part. It will still find it. Try and let me know if it works.

I noticed you added the React tag to your question. If your back-end and front-end are running on different ports you have to setup a proxy in your front-end package.json file. It would look something like this:

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:3000/api",
  "dependencies": {...},
  ...
}

Now you can fetch("/code/add") for example and if react does not find that route defined on the front-end it will look in proxy routes and do this by itself: fetch("http://localhost:3000/api/code/add")

Related