I've just started with React to see what all the fuss is about. I was quite impressed until I came across JSON web services and security. I am trying both fetch and axios.
So have two questions and a little bit of background for context.
How do you access a local web service using react and avoid the "opaque" response problem.
//react app running on http://localhost:3000 const result = await fetch("http://localhost/api/data.php", { mode: "no-cors" });//opaque response //this doesn't work either, I get the cors error //const result = await fetch("http://localhost/api/data.php");//opaque const json = await result.json(); ....How do you secure access to your web services from a React app. Both when working locally and when deployed.
I can understand the issues and problems with CORS etc, there are loads of articles I can find telling me what the problem is and why, which I totally get. I just couldn't find anything with a solution.
Background
- React doesn't have any (built-in) server functionality so connecting to a database isn't possible.
- You can't seemingly have your react app on and your web service both running on
http://localhostit just won't work. - Will I have the same problem when deployed e.g.
https://myreactapp.comtrying to talk tohttps://myreactapp.com/api(or something of that ilk).
This appears to be borne out by the fact that every single tutorial, article, and example uses either a local JSON file or an external unrelated URL to get JSON data. Also, I could not find anything that even suggests it's even possible, which then gives rise to security questions.
My go-to for security is cookies. Simple straightforward and robust. I mean if Microsoft and Google use this approach it has some mileage.
So an additional security question is
- If your react app and your web services have to be on two different domains, how will my cookie-based security then work?
I have read and watched several hours of tutorials and articles and none explain this part. They are all great and show you how to get going with react, but I am developing the react and web service locally in tandem. I've used the same approach with C# and PHP projects and both work perfectly with no issues.
I am happy to be told I have misunderstood or I am just plain wrong, but I would ask you provide a solution or link to an article to back it up.
Obviously, if I find a solution I will post it here.
You can use a reverse proxy server. If you are developing, use a dev server such as webpack-dev-server, See here, let the proxy server send the request to the secure remote sever instead of your app. In the production, you need use a production-ready reverse proxy server, such as nginx. Then for your app, no CORS issue any more.