React Proxy error: Could not proxy request /api/ from localhost:3000 to http://localhost:8000 (ECONNREFUSED)

前端 未结 6 1413
忘了有多久
忘了有多久 2021-01-17 08:02

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 r

6条回答
  •  别那么骄傲
    2021-01-17 08:26

    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')
          }
        })
      )
    }
    
    

提交回复
热议问题