React and nginx: refused to connect to localhost

I have my React (frontend) and Django REST (backend) running on a remote Ubuntu server with nginx. I also have a simple reverse proxy defined in conf.d/bookmarks.conf to manage all of that:

server {
    listen 80;
    listen [::]:80;

    location /api/ {    # Backend
        proxy_pass http://127.0.0.1:1337/api/;

    }

    location / {    # Frontend
        root        /var/www/bookmarks/html/;
        index       index.html;
        try_files   $uri $uri/ /index.html;
    } 
}

I run my Django app with runserver python manage.py runserver 127.0.0.1:1337, and React static files are stored in the folder described above

I try to connect to API with React:

const generateOpendIdLink = async () => {
      const generateOpendIdLinkEndpoint = 'http://127.0.0.1/api/opendid-link-generator/';
      const requestOptions = {
        method: 'GET',
        headers: {'Content-Type': 'application/json'},
      };

      try {
        const response = await fetch(generateOpendIdLinkEndpoint, requestOptions);
        if (response.status == 200) {
          ...
        };
      } catch (error) {
        console.log(error);
      };
    };

And get an error

GET http://127.0.0.1/api/opendid-link-generator/ net::ERR_CONNECTION_REFUSED

This is quite odd, because I could connect to API from the web no problem: running the same GET on the server IP address http://XX.XXX.XX.XX/api/opendid-link-generator/ from Postman works as expected. This is also true when I change 127.0.0.1 for the server IP in the React code, it all starts to work.

I also set ALLOWED_HOSTS = ['*'] for test purposes while trying to solve this problem, and it did not help. Does anyone know what could be the source of the problem?

I don't know anything about javascript, but let me give it a shot:

const generateOpendIdLinkEndpoint = 'http://127.0.0.1/api/opendid-link-generator/';

This definition does not include the port! Most likely it looks up the default http port at :80 then. Try to include the port and let me know!

Back to Top