Fixing CORS error issue axois.get MissingAllowOriginHeader - reactjs

Okay so:
I'm running a LightSail instance at www.gethatext.com.
FrontEnd - React, BackEnd - Django
On the homepage, I'm making 2 get requests to the Django server.
It is important to say that both Django & React are being served in the apache server.
.conf file of apache (http & https)
ProxyPass /api http://localhost:8000. # Django.
ProxyPassReverse /api http://localhost:8000 # Django.
ProxyPass / http://localhost:3000/. # React.
ProxyPassReverse / http://localhost:3000/. #React.
So I investigated and read that i need to add the following to the .conf file in either <Directory>, <Location> or <VirtualHost>. and so I did (and restarted all services of source).
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
BUT it did not help.
But when I'm making the same request from POSTMAN in my computer I get a the expected response (After running from the instance terminal python manage.py runserver 0.0.0.0:8000)
I Also added https://cors-anywhere.herokuapp.com to my request
So it looked like:
axois.get("https://cors-anywhere.herokuapp.com/https://gethatext.com/api/account/quantity/")....
and surprisingly IT WORKED..
But it doesn't feel like a good practice and also in terms of data privacy.
So I wonder what is it the problem here?
Is it related to that, that Django and React are both served in the same apache service?
Also add to axois header:
"Access-Control-Allow-Origin": "*"
But with no luck
Browser console error:
Cheers guys & Thanks in advnace.

So the solution for this one was
Adding:
"proxy" : "https:my-domain.com".
to the package.json and in the axios requests.
axios.get("/upload/quantity/").then()...
And it worked

Related

Using Create-React-App with Apache VirtualHost

I am trying to develop a project for a company. This company has an API that only allows requests from two sources: Their own host, and xyz.localhost.
At first, I developed the project with jQuery only (loaded in via CDN). With an Apache VirtualHost setup, this worked -- I could access the API.
Now, I want to refactor the project and use React with it. I used create-react-app to create a react directory.
The problem is: I can get create-react-app to use xyz.localhost, but I am still getting the CORS error message in Chrome:
Access to fetch at 'http://api.thatcompany.com/search?search=a'
from origin 'http://xyz.localhost:3000' has been blocked by CORS policy
Has anybody any ideas how to make it work?
Thank you in advance.
/private/etc/apache2/httpd.conf:
# Virtual hosts
#Include /private/etc/apache2/extra/httpd-vhosts.conf
Include /private/etc/apache2/vhosts/*.conf
/private/etc/hosts:
127.0.0.1 xyz.localhost
255.255.255.255 broadcasthost
::1 xyz.localhost
/private/etc/apache2/vhosts/xyz.localhost.conf:
<VirtualHost *:80>
DocumentRoot "/Users/MYUSERNAME/dev_projects/MY-REACT-APP/public"
ServerName xyz.localhost
<Directory "/Users/MYUSERNAME/dev_projects/MY-REACT-APP/public">
AllowOverride All
Require all granted
</Directory>
<filesMatch "\.(html|htm|js|css)$">
FileETag None
<ifModule mod_headers.c>
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</ifModule>
</filesMatch>
</VirtualHost>
My create-react-app start script:
"scripts": { "start": "HOST=xyz.localhost react-scripts start" }
I found a workaround.
I simply pointed the VirtualHost to the build folder of Create React App, this worked and served me the static files.
Editing the code was pretty tiresome, as I had to run npm run Build after every update.
Luckily, I found the npm watch module. With that, create react App would rebuild on every save. I still have to wait a second between save and refreshing the browser, and it’s absolutely not comparable to using create react app on its own, but it was a good enough solution!

MERN Stack on a LAMP Droplet (DigitalOcean)

I have a MERN application split into:
1. client folder : Front-End code (REACT app)
2. server folder : API Code (Express, NodeJs)
For some reason, front-end calls the /api part of the app, but does not return a response. Is the issue in Apache2 setup? or something in the react app. And how is the link usually done between ExpressJs (Backend) and the ReactJs (Frontend).
Routing is setup through an Apache2 Reverse Proxy
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com/
Options -Indexes
ProxyRequests on
ProxyPass /api https://example.com:3000/
ProxyPassReverse /api https://example:3000/
ProxyPass / https://example.com:7000/
ProxyPassReverse / https://example:7000/
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
</VirtualHost>
</IfModule>
Just to clarify in picture of what I'm trying to achieve:
I think the issue is that you've forgotten to prepare your React App for production. You spent all the time developing it and using react-scripts-start or something similar. When you are done developing you have to run react-scripts-build so that your code can be transpiled into something the browser can read. Web browsers don't read things like import and require.
Here's info on preparing for production (it's very simple)
https://create-react-app.dev/docs/production-build
And here's info on how to integrate it with your back end:
https://create-react-app.dev/docs/deployment#other-solutions
Essentially:
In your client folder run
npm build
In your server.js add
app.use(express.static(__dirname + '/build')
Now a client requests your index.html from your back end server and it serves your react app. Added benefit: no more CORS errors. Any work-around you did for CORS you should probably take it out.

Reverse Proxy with Apache ProxyPass redirects instead of transparently passing through

I got a web application running inside a Tomcat at http://<server>:8080/app/portal/.
I want the world to see this application through the URL http://<server>/portal/.
To do this, I set up a Reverse Proxy with Apache 2.2. According to the documentation for ProxyPass I expect the reverse proxy to pass all requests through transparently. My browser should never know about the Tomcat URL.
Here is my configuration:
No virtual hosts, I added these lines to my httpd.conf
<Location /portal/>
AllowOverride All
RewriteEngine On
ProxyPass http://server:8080/app/portal/
ProxyPassReverse http://server:8080/app/portal/
</Location>
When I use Firefox to open http://<server>/portal/, I get a 302 Moved Temporarily, and all follow-up calls go from my browser directly to http://<server>:8080/app/portal/. My browser points to this URL.
This is not what I expected of a Reverse Proxy. Did I do the configuration wrong or did I misunderstand the purpose of Reverse Proxies? What should I do to get my desired behavior?
You forgot to add the following option in your reverse proxy configuration:
ProxyPreserveHost On
You can achieve the same behavior with Url Rewriting but it's not recommended in the documentation.
I tried to comment the answer from davidethell, but could not get the lines correctly formatted, so here is what I found out:
The problem was that the reverse proxy seems only to work to the URL where the War is deployed in my Tomcat, and NOT to the servlet inside the Tomcat. This leads to 2 rewrites, one of them the reverse proxy and one just rewriting everything behind that.
RewriteEngine On
RewriteRule ^/portal/$ /portal/portal
RewriteRule ^/portal(.+) http://<server>:8080/app$1 [P]
Have you tried using the mod_rewrite Proxy option instead of ProxyPass? Something like:
RewriteRule ^$ http://server:8080/app/portal/ [P]
For my https server, I used:
SSLProxyEngine on
ProxyPass / https://server:7000/
ProxyPassReverse / https://server:7000/
ProxyPreserveHost On
The SSLProxyEngine manage the https behavior from the real serrver (with port 7000 in my case). Others are just managing the redirection without changing url.
Now, In navigator I can access to https://server/ which is in reality https://server:7000/

Spring WebFlow2 fronting with Apache2 SSL produce http urls instead of https

I have Apache2 SSL which is fronting Spring webapp as follows:
ProxyPass / http://localhost:8080/
ProxyPassReverse / http://localhost:8080/
All works fine... i mean all links ... are correct, and in general webapp works, so the problem is not a matter of an application or SSL..
Except starting/cancelling webflows: they produce http URLs instead of https://
I found one topic here:
forum.springsource.org/showthread.php?70730-Webflow-2-0-and-reverse-proxy
They say it is not a problem of Spring WebFlow...
What is a workaround in this situation?
Providing that all requests to the Tomcat connector are received via SSL terminated at httpd then you can add the following to your connector:
scheme="https" secure="true"
This tells Tomcat to treat the connection as if it was received over an SSL connection direct to Tomcat. This is required when proxying over http since there is no mechanism within http to pass the SSL info to Tomcat. There are ways to pass some of this info via http headers. Look at the SSLValve docs in Tomcat.
Alternatively, using AJP will work since AJP passes SSL information from httpd to Tomcat.

GAE dev_appserver.py over HTTPS

Has anyone cracked how to get HTTPS working on the dev_appserver.py? I need it for Facebook canvas app testing. I've had a search of the docs and nothing suggests there's a way to do it (sticking 'secure' in the app.yaml doesn't nothing locally).
I was think there may be a way to proxy it, but has anyone got any experience of this?
The dev_appserver doesn't support HTTPS. The only practical way to do this is to set up a reverse proxy in front of your app - such as with nginx or Apache - and have it proxy SSL traffic to your app.
I know this is late, in case anybody else finds this question:
ngrok is quiet easy to setup for a custom reverse HTTPS proxy..
The only downside is that my webapp2 application still believes it's being served over HTTP, so using redirect() doesn't work well because it resolves relative URLs to absolute URLs using request.url.
My workaround was to overwrite RequestHandler.redirect as follows:
class BaseRequestHandler(RequestHandler):
def redirect(self, uri, permanent = False, abort = False, code = None, body = None):
if uri.startswith(('.', '/')):
base_url = self.request.url
if base_url.startswith('http://'):
base_url = 'https://' + base_url[7:]
uri = str(urlparse.urljoin(base_url, uri))
super(RequestHandler, self).redirect(uri, permanent, abort, code, body)
I needed a BaseRequestHandler class anyways for implementing other utility functions.
I put this in my Appache httpd.conf to proxy the connection:
<Location /myproject/>
ProxyPass http://localhost:8080/
</Location>
Now going to https://localhost/myproject/ in my browser worked.
Note: SSL needs to be enabled on your Apache server. On my OS X machine I uncommented out the line Include /private/etc/apache2/extra/httpd-ssl.conf in /etc/apache2/httpd.conf and ran sudo apachectl restart

Resources