Search code examples
reactjsfetch

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


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!


Solution

  • 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")