I'm using pretty small create-react-app running on port 3000 setup to proxy requests to backend server running on port 8080.
If I put in the browser address bar http://localhost:3000/api/me
I get back the index.html page but if I use fetch API to get /api/me
it try to call to by backend.
The problem is that I have to authenticate with the backend which will set a cookie but since I can't access the login page on http://localhost:3000/login
I can't get the cookie.
On a different project which I've eject from create-react-app I have small file to run webpack-dev-server wih the configuration
proxy: {
"*": "http://localhost:9191"
}
which does proxy requests even when put into the browser address bar.
Is it possible to create such setup in create-react-app?
Closer look into create-react-app code reveal that this is by design:
For single page apps, we generally want to fallback to /index.html. However we also want to respect
proxy
for API calls. So ifproxy
is specified, we need to decide which fallback to use. We use a heuristic: if requestaccept
s text/html, we pick /index.html. Modern browsers include text/html intoaccept
header when navigating. However API calls likefetch()
won’t generally accept text/html. If this heuristic doesn’t work well for you, don’t useproxy
.
Running GET of http://localhost:3000/api/me
inside REST Console extension return the correct result.
Further reading about Fetch API and cookies reveal that I have to include the parameter credentials:true to send cookies:
fetch('/api/me', {
credentials: 'include'
})
Yes it is possible:
"proxy": {
"/api": {
"target": "<url>",
"ws": true
}
},
See https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#configuring-the-proxy-manually
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With