CORS Issue using flask_socketio and React - reactjs

I am getting a CORS error when trying to connect my frontend react with my backend flask.
My backend should be accepting requests from all origins, and my front end is simply just trying to connect, and hopefully display a form.
This is more of a cors issue, and I tried all sorts of things such as origins=None, origins=*, taking away origins completely, etc. etc. and nothing changes. It does look like the socket is connected, but not sure how to, or where to manually set the header?
Error Message
Frontend :3000 - React
Server :5000 - Flask-socketio

Following the below method helped to avoid CORS issue in flask.
app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
Doc - https://flask-cors.readthedocs.io/en/latest/

Related

CORS policy is allowed in app.py but still not working

The front-end app is built on ReactJs and development server is running on http://localhost:3000. The back-end API is built with Flask 2.0.2 and is running on http://localhost:5000
In app.py file, the CORS has been allowed as mentioned in the documentation like:
CORS(app, resources={r"*": {"origins": "*"}})
When I try to submit the login form I still get the following error:
if you Enables CORS on your backend api , it should work.
I don't think this is an issue with your react frontend application.
cors is a security measure put in by browsers.
You could bypass the Cross-Origin-Policy with chrome extension but it's not advisable -
Try this on your backend API:
Ensure you have flask cors installed
create a configuration dictionary like this
api_v1_cors_config = {
"origins": ["http://localhost:5000"]
}
You can then set a global cors for your app like this
CORS(app, resources={"/api/v1/*": api_v1_cors_config})
// this would allow all methods, origins

How to fix "net::ERR_CERT_AUTHORITY_INVALID" when sending a request to an https:// API?

I have a React application (create-react-app) running on http://localhost:3000/ and I need to send a request to an API (Java with Spring Boot) that is available on "https://review-feature-...api/partner".
However, when I send the request, I get the following error on my Chrome console:
POST https://review-feature-...api/partner net::ERR_CERT_AUTHORITY_INVALID
I've tried to change my React application to run on https://localhost:3000, but it doesn't work because I have a Keycloak authorization server running behind my React app, so I have to find a way to send the request using http://localhost:3000/ anyway.
I've also tried to use the following environment variables (How can I provide a SSL certificate with create-react-app?) but it doens't work.
SSL_CRT_FILE=.cert/server.crt
SSL_KEY_FILE=.cert/server.key
Thanks in advance.

React + redux app deployed on heroku but backend/api not working

here is my app link https://course-s.herokuapp.com/ and here is my Github repo https://github.com/shaikafroz016/Course-S . The app work perfectly in localhost whit express, MongoDB Atlas, and node server as a backend and react-redux as a frontend but when I am trying to run this on Heroku my says's failed to fetch whats the problem.
EDIT:
I have mentioned the base url as localhost:3000 in my client so should i have to add heroku app link to base url? can you please help me what to do. And also when i am trying the app with backend localhost (localhost:3000) it work just fine as i close my local server the heroku app says faild to fetch
This must be because of CORS (Access-Control-Allow-Origin), here's a workaround :
run npm install cors
and then add this to your app.js file :
var cors = require('cors')
app.use(cors())
Be sure to add this before all your requests definition (app.get, app.post, etc...)
Now CORS is enabled.
The Access-Control-Allow-Origin header determines which origins are allowed to access server resources over CORS.
Explanation : https://medium.com/#alexishevia/using-cors-in-express-cac7e29b005b

Access-Control-Allow-Origin Error Only on a Single Route, Only When Deployed to GAE

I'm using google app engine to host both my frontend and my api backend. I'm getting the following errors when I'm polling the "slicingdone" route on my backend:
bootstrap e65cef5bb029055e1719:2 GET
https://playloopsbackend-217106.appspot.com/playloops/slicingdone 502
send # bootstrap e65cef5bb029055e1719:2
/videotogifs:1 Access to XMLHttpRequest at
'https://playloopsbackend-217106.appspot.com/playloops/slicingdone'
from origin 'https://playloopsfrontend.appspot.com' has been blocked
by CORS policy: No 'Access-Control-Allow-Origin' header is present on
the requested resource.
I poll the slicingdone function to figure out when trimming of a video on my backend is finished. It works locally but is presenting the above errors when deployed to gcloud.
slicingdone function on my backend looks like this(Express):
slicingdone(req, res, next) {
if(slicingIsDone == true){
res.status(200).send('true');
slicingIsDone = false;
}else{
res.status(200).send('false');
}
}
*Every other route on my backend works fine even when deployed. I have similar functions on the backend that manipulate videos using ffmpeg in different ways. I have whitelisted my frontend url on my backend, so I'm not sure why I'm getting these CORs errors. I store the video results in google cloud storage--perhaps I need to add my backend url to google cloud CORS whitelist?
Any help is much appreciated! Thank you!

CORS request did not succeed - react

I make this API request , using axios in ReactJS
axios.post(`${API_URL}/valida_proximo`, {
id: images.map(image => image.id)
},
getAxiosConfig())
// this.setState({ images, loadingAtribuiImagens: false})
}
It works really well in Google Chrome, but on Firefox I receive an error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/valida_proximo. (Reason: CORS request did not succeed).[Learn More]
What can I do?
This is my API
#blueprint.route('', methods=['POST', ])
#jwt_required()
def index():
if request.json:
id_usuarioImagem = request.json.get('id')
imagens_selecionadas =
UsuarioImagem.query.filter(UsuarioImagem.id.in_(id_usuarioImagem)).all()
if imagens_selecionadas:
for imagem_selecionada in imagens_selecionadas:
imagem_selecionada.batido=True
db.session.commit()
return 'ok', 200
return 'error', 400
CORS errors are usually associated with cross domain requests and something not configured to accept a request on the recipient side of the request. The fact that chrome is working but firefox doesn't seems rather strange.
This was a method I used:
Open Firefox browser and load the page.
Perform the operation which is throwing Cross Origin Request Security (CORS) error.
Open firebug and copy the URL which is throwing Cross Origin Request Security (CORS) error.
Load the same URL in another tab in same Firefox browser.
Once you open the URL in another tab will ask you to add the certificate.
After adding the certificate will resolve Cross Origin Request Security (CORS) error and now you will not be getting this error.
I'm not too familiar with Axios, but it looks like you're making a post request from your React to your Flask backend. If the front-end and the backend are on different ports (like your Flask seems to be on PORT 5000), then you're making a CORS request.
With CORS, depending on what you're posting, you might need to include some Access-Control headers in your Flask response object. You can do this either manually, or just pip-installing and using the 'flask-cors' package. Import the package into your app factory and use it like so (see their docuementation for more info):
from flask_cors import CORS
def create_app(test_config=None):
app = Flask(__name__, instance_relative_config=True)
CORS(app)
The request might also get 'preflighted' with an 'OPTIONS' request, also depending on the nature of your POST. More information would be helpful
This is a bug in firefox.
if you follow the link (MDN) in the error msg . you will find:
What went wrong?
The HTTP request which makes use of CORS failed because the HTTP connection failed at either the network or protocol level. The error is not directly related to CORS, but is a fundamental network error of some kind.
which i read as the connection failed and not a problem with CORS settings.
you will just have to ignore the error message until firefox gets it fixed.
The error has something to do with refreshing the page and long polling requests or service workers and polling requests.
If anyone sees this question again, I had this problem because I made a request to https://url instead of http://url

Resources