49

I have a React frontend that uses jwt to authenticate with the Django backend. The backend works and is connecting just fine using django views, but when I try to proxy a request from React, it gives me a Connection Refused error.

Proxy error: Could not proxy request /api/auth/token/obtain/ from localhost:3000 to http://localhost:8000 (ECONNREFUSED).

Connecting to http://localhost:8000/api/auth/token/obtain/ works normally. And sending a POST request with Axios also works normally and returns the token json. But when I proxy it with node, it doesn't work.

In my package.json I have:

  "proxy": {
    "/api/*":  {
      "target": "http://localhost:8000"
    }
  },

Edit: Public repo. You can run easily if you have docker installed. (uses 1 image and 2 containers). After cloning just run docker-compose build, then docker-compose up.

Edit2: Headers of request:

*General*
Request URL: http://localhost:3000/api/auth/token/obtain/
Request Method: POST
Status Code: 500 Internal Server Error
Remote Address: [::1]:3000
Referrer Policy: no-referrer-when-downgrade

*Response Headers*
HTTP/1.1 500 Internal Server Error
X-Powered-By: Express
Date: Mon, 30 Apr 2018 21:23:17 GMT
Connection: keep-alive
Transfer-Encoding: chunked

*Request Headers
POST /api/auth/token/obtain/ HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Content-Length: 45
Pragma: no-cache
Cache-Control: no-cache
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
Content-Type: application/json
Accept: */*
Referer: http://localhost:3000/login
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,fr;q=0.8,ja;q=0.7
4
  • It would be helpful if you posted your Django and Node code. Commented Apr 30, 2018 at 20:36
  • @MattMorgan Sorry. Added. Commented Apr 30, 2018 at 20:47
  • Not sure, and can't quickly get this running locally. CRA docs indicate your target pattern might be wrong. Have you tried: "/api" instead of "/api/*"...wondering if it's trying to match on api/only-one-more-element Commented Apr 30, 2018 at 21:13
  • @MattMorgan doesn't work with /api, /api/ or /api/*, or with just "proxy":"http://localhost:8000". Commented Apr 30, 2018 at 21:27

15 Answers 15

37

So the issue was since both the Node dev environment and the Django dev environment were running in separate docker containers, so localhost was referring to the node container, not the bridged network.

So the key was to use container links, which are automatically created when using docker-compose, and use that as the hostname. So I changed it to

"proxy": {
    "/api":  {
        "target": "http://django:8000"
    }
},

And that worked, as long as you launch both containers with the same docker-compose command, otherwise you have to manually specify external_links in your docker-compose.yml file.

Sign up to request clarification or add additional context in comments.

2 Comments

I had the same issue, for me I got an error when the proxy in package.json was an object so it had to be a string, but http://<container-name>:<port> worked great! Thank's a lot
That works perfectly, as intended when you think about it since the docker doc does say compose handles hostname resolution. Still a bit weird that Localhost would not work even with separate containers.
30

I faced a similar issue but in Mac machine. I changed localhost to 127.0.0.1 in the package.json and that worked for me as below:

"proxy": "http://127.0.0.1:5000"

4 Comments

Tried this and doesn't work. React is still trying to send requests to localhost:3000
This worked for me in a Flask project. Thank you!!!!!!!!
Worked for me for my Django / React project! But why?
Didnt work fro NodeJS
15

I'm running into the same problem as well. Most search results mention adding "secure": false or "ignorePath": true to your proxy config. Something like this:

"proxy": {
    "/api/*":  {
      "target": "http://localhost:8000",
      "secure": false
    }
  },

May be worth a try but unfortunately none of this worked for me. Although each address (http://localhost:3000 and http://localhost:8000) work completely fine in the browser, maybe since the container is actually proxying it needs to use a Docker address?

EDIT--

Alright I think I figured it out. I believe it did have to do with the container to container communication. Looking in your docker-compose, your api server is called django. Change your package.json file to this:

"proxy": {
    "/api/*":  {
      "target": "http://django:8000",
      "secure": false
    }
  }

2 Comments

I actually fixed this yesterday and posted my answer on how I fxied it. For me it was because the two servers were running on different node containers, so localhost, didn't refer to the same host as django.
This answer helped me immensely in solving my issue today, so thanks a million @VincentJr
12

Didn't actually get the answer here I was looking for but had an alternative solution work for me. I think it's specifically related to Node v17, as that's when it started happening for me but the solution was pretty simple.

I updated:

"proxy": "http://localhost:8000"

To:

"proxy": "http://127.0.0.1:8000"

In case it's relevant (I don't think it is) - I was proxying to a Django server.

2 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
This worked for the me, the proxy seems to understand 127.0.0.1 but not localhost. Also remember to include the http:// protocol
4

If you don't feel like setting up docker compose, you can also use a docker network:

create network and run docker containers within that network

docker network create webapp_network

docker run -d -p 5000:5000 --name webapp_backend --network webapp_network webapp_backend_image

docker run -d -p 3000:3000 --name webapp_frontend --network webapp_network webapp_frontend_image

Added a line in package.json of my frontend React webapp:

"proxy": "http://webapp_backend:5000"

note you can now refer to your backend using the container name instead of localhost

Comments

2

If your on a newer version CRA 2.0+ you'll need to do this via a manual proxy. https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development#configuring-the-proxy-manually

Comments

1

Could see the error after upgrading yesterday Docker to version v19.03.13 (on Mac), restarting Docker fixed the issue. The application also runs Node.js/React, but not Django. Basically, I had issues with connection to MongoDB Atlas related to authentication/fetching anything from the cloud database.

Comments

1

Choosing the exact value for localhost to populate the "target" property is mostly the solution (it can be localhost, 127.0.0.1, [::1] ).

A mac user should type in terminal to get the solution:

sudo lsof -iTCP -sTCP:LISTEN -n -P

Comments

0

The correct answer will be to use manual proxy with

  1. target = docker address django:4000
  2. correct HOST header localhost:8000

because if Django uses reverse function which returns absolute url

reverse('preview-mail', args=[mail.pk],request=request)

you need to have correct HOST header for it, or you may get the result URL like https://django:4000/your-url`

const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    proxy('/api', {
      target: 'http://django:4000',
      changeOrigin: true,
      secure: false,
      pathRewrite: {
        '^/api': ''
      },
      onProxyReq: function (proxyReq, req, res) {
          proxyReq.setHeader("host", 'localhost:8000')
      }
    })
  )
}

Comments

0

If you're working on a MERN stack app, make sure you're not in the client folder. You need to be in the root. While in the root, run this command in the terminal. npm run start:dev

1 Comment

Brilliant. Thank you. I forgot I was in the client folder of my app... 🤣
0

For NodeJs backend this can be solved by adding a line of code in the package.json file of the backend

"devstart": "nodemon server.js --ignore './location of frontend react directory'",

Comments

0

I ran into this problem when I changed the webserver address. At first I had a localhost, and everything worked fine. In order for me to access my web server from other machines, I changed its address to 0.0.0.0 after that I got this problem. It helped me to change the proxy settings from localhost to 127.0.0.1

Comments

0

I had this same issue. my resolution was changing http://localhost:8000 to http://127.0.0.1:8000

Comments

0

In your docker-compose.yml add the network bridge configuration

version: '3'
networks:
  my-network:
    driver: bridge
services:
  frontend:
    image: username/react-frontend:1.0
    ports:
      - "3000:3000" // Map port 3000 on host to port 3000 on container
    depends_on:
      - backend
    networks:
    - my-network
  backend:
    image: username/express-backend:1.0
    ports:
      - "8000:8000"  // Map port 8000 on host to port 8000 on container
    networks:
    - my-network

Then, in your frontend package.json

"proxy": "http://backend:8000" //NOT http(s)

Comments

-3

In my case, my server was running on port 3001, but I had "proxy": "http://localhost:3000" in the package.json file of my React fronted project 😆

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.