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
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
}
}
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"
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
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.
The correct answer will be to use manual proxy with
django:4000
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')
}
})
)
}
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.