-1

I am working on my app, and while I use yarn run dev I cannot make API calls to the API routes defined by me. The app runs on port 3000, but the server on 3500. If I hardcode the "3500" into the API call, it works, like this:

fetch('http://localhost:3500/api/config').then(r => r.json());

if I leave it like this it doesn't work:

fetch('/api/config').then(r => r.json());

If I deploy the app online or if I use yarn run dev-server, there is no problem, it works. Is this a normal thing to happen? Should I try to fix this, or is it something normal?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Bogos Robert
  • 193
  • 2
  • 9

1 Answers1

0

This happens because when you do

fetch('/api/config').then(r => r.json());

It will try to request localhost:3000/api/config, and that doesn't exist because your server is running on 3500 and not 3000. When you hardcode the port the request will be sent to the correct port, so it will work.

  • Yes, it will work locally, but if I leave it like this, when I deploy live it won't work – Bogos Robert Aug 23 '21 at 16:15
  • @BogosRobert Use a variable to change the server URL, if it's development then set it to `localhost:3500`, if it's production set it to your production URL. – Murtaja Ziad Aug 23 '21 at 16:23
  • This is a solution, but not such a good one , because I would need to declare that variable in all the files that I want to make api calls , I was looking for a more solid solution – Bogos Robert Aug 23 '21 at 16:36
  • You can use a global variable, for example `window.serverURL`. – Murtaja Ziad Aug 23 '21 at 16:56