Fetch API not working with localhost/127.0.0.1

I just had the same problem. I managed to get this working by adding "proxy": "http://localhost:4000" to package.json.

Then you can write requests like fetch('/api/todos').

They explain it good here.


If you're trying to send a request to localhost, and you are hosting your server on localhost, then you don't need to specify the url, you only need to tell fetch() your path.

For example, my api end point is http://localhost:8082/api/config, then i would do fetch('/api/config').

Here is a link to fetch method, link


When you write localhost it calls your (localhost) machine (on which the browser is present) because the js code is running in your browser.

You should create a domain/sub-domain for your API endpoint and use it instead of localhost or continue to use the hard-coded IP address.

You should also allow only your frontend website domain in the allowed origins for your backend. Ex. your website can be www.example.com and backend url can be www.api.example.com. You should allow only www.example.com as the origin which can be served through www.api.example.com. You will need to configure this in the backend.