I'm using OpenFire with the REST API plugin installed.
I'm attempting to get a list of chat rooms through an AngularJS $http call to http://localhost:9090/plugins/restapi/v1/chatrooms
with the proper Authorization header set in the $http.defaults.headers.common property.
When the call is made, I get the following error:
OPTIONS http://localhost:9090/plugins/restapi/v1/chatrooms 401 (Unauthorized)(anonymous function) # angular.js:10722sendReq # angular.js:10515serverRequest # angular.js:10222processQueue # angular.js:14745(anonymous function) # angular.js:14761Scope.$eval # angular.js:15989Scope.$digest # angular.js:15800(anonymous function) # angular.js:16028completeOutstandingRequest # angular.js:5507(anonymous function) # angular.js:5784
XMLHttpRequest cannot load http://localhost:9090/plugins/restapi/v1/chatrooms. Response for preflight has invalid HTTP status code 401
The truly annoying issue is, that when I build the same request through Postman, it works perfectly and the expected response is received but inside the browser (whether through $http, or a call to window.fetch through the console) I keep getting that error.
Supposedly, the OpenFire REST API supports CORS (I went so far as to check the plugin source code), but nothing seems to help.
I'm the developer of REST API plugin. You are right that the REST API supports CORS, and it is possible to call it directly from angular js. The mentioned problems (preflight request) will by done by your browser. I just fixed the issue that the OPTION request don't need to auth.
Checkout the REST API version: 1.1.7
I suggest you to compare the fiddler request and the browser request (headers + body).
It should work if they are 100% identical..
Related
I created a DynamoDB table and attached 3 lambda functions to it. I'm trying to call these functions by attaching an API Gateway trigger to them. I created a Rest API and then the get method. Afterwards, I deployed the API and the API link works as intended. I'm now trying to call the API using a Axios in React.
axios.get("Link")
.then(res => {
console.log(res);
})
The problem is that whenever I try to run this on a local server, I get the following error.
Access to XMLHttpRequest from origin 'http://localhost:3000' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
I've tried enabling CORS on the API Gateway but that doesn't work either. I know the problem lies somewhere in the backend but I can't figure out what I'm supposed to do.
If you have enabled CORS then this is expected behaviour. CORS will not allow other domains to access your API unless otherwise configured.
Check how to properly configure CORS on API-Gateway from here: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html
For your development / test / learning environment you can disable* CORS and then you can call API from localhost.
More troubleshooting on API Gateway CORS issue:
https://aws.amazon.com/premiumsupport/knowledge-center/api-gateway-cors-errors/
*It is not recommended based on security grounds
Try opening chrome with CORS security disabled.
Mac OS:
open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --args --user-data-dir="/tmp/chrome_dev_test" --disable-web-security
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
I have a web site which is served over an https protocol. This is written in angularJs. The Website is calling an asp.net web api service over http, and then I'm getting this error:
angular.js:10765 Mixed Content: The page at 'https://example.com/forms/#/question-set-4#topOfThePage' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://webapiaddress/api/ControllerName/GenerateCaptcha'. This request has been blocked; the content must be served over HTTPS.(anonymous function) # angular.js:10765r # angular.js:10558g # angular.js:10268(anonymous function) # angular.js:14792$eval # angular.js:16052$digest # angular.js:15870$apply # angular.js:16160g # angular.js:10589T # angular.js:10787w.onload # angular.js:10728
angular.js:10765 XMLHttpRequest cannot load http://webapiaddres/api/SomeController/GenerateCaptcha. Failed to start loading.
So the error suggests for me that I should serve the web api self host over an https addres. So in the config of that web api self host I'm changing it to https//webapiaddres/
But then I'm getting this:
angular.js:10765 GET
https:/webapiaddress/api/SomeController/GenerateCaptcha
net::ERR_INSECURE_RESPONSE
What am I doing wrong? Why is this happening. Strange thing is that that this does not scream that I don't have CORS enabled, but this could be because of the fact that this web api selfhost and the site is on the same server. I can't find any simmilar problem to mine in google.
I've managed to solve the problem with my colleage and it was very simple. It did not came up at first glance. I've ran the address of the web api in the chrome browser and there there was an request for accepting an certificate. When I did that everything went smooth. This is the work for our administrator not from the code, but this was quite interesting experience.
I am using a flask server with an angular front end. Up until recently, I was running the project on my local and had no issues.
I now moved my project to a remote server and have been getting the following error. I am not sure what i'm doing wrong:
My error:
XMLHttpRequest cannot load http://ec2-..../api/loginStatus/. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8100' is therefore not allowed
access. The response had HTTP status code 503.
The snippets of my flask server side code (where I am adding my headers to the response is given below):
#app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin','http://localhost:8100')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
response.headers.add('Access-Control-Allow-Credentials', 'true')
return response
I use both restangular and $http methods in my front end angularjs.
I have added the following lines in the .config of my main module:
.config(['RestangularProvider', '$stateProvider', '$urlRouterProvider','$httpProvider',
function(RestangularProvider, $stateProvider, $urlRouterProvider,$httpProvider) {
//$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.headers.common['Access-Control-Allow-Origin'] = "http://localhost:8100";
$httpProvider.defaults.withCredentials = true;
$httpProvider.defaults.headers.common = 'Content-Type: application/json';
delete $httpProvider.defaults.headers.common['X-Requested-With'];
Would someone be able to help me out here? I've referred to a lot of material and I am not sure what i'm doing wrong.
PS: I am getting 200 status messages on my server. I am therefore assuming that the error is in my front end and not my server side. Please correct me if I am wrong
Regards,
Sunil
EDIT
Hi everyone, I have solved the issue. I would like to thank #Mathijs Segers and #Hassan Mehmood for their inputs.
It turns out that there was a nginx configuration issue which led to the server becoming unavailable.
Firstly, there was an issue with the symbolic link that was being created for the flask backend (I am running my server side through a git repo on /home/username and then creating a symbolic link at /var/www/sitename.com
I was also throttling the number of requests that can be sent in a second (users could send only 1 every 2 seconds) resulting in the 503 error.
The original code I put up worked fine after I fixed it.
Eyooo, it is actually on your server side. You need to provide correct headers.
So you've tried this, I have no experience with flask but this I don't like;
response.headers.add('Access-Control-Allow-Origin','http://localhost:8100')
for testing purposes I suggest you just change the http:// part, to *
so
response.headers.add('Access-Control-Allow-Origin','*')
If that doesn't work verify that the header is actually being set, you could use a different program which doesn't care for CORS like postman or directly calling it in the browser if it doesn't depend on Accept headers.
here is some more readings about what it all is about.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
EDIT:
Ok silly of me: The response had HTTP status code 503.
This part in the error actually states what kind of response your server is giving, so currently there is an error on your server side. This happens when it is f/e down or what not.
So it seems that you're not doing anything strange, but your server side seems broken.
XMLHttpRequest cannot load http://ec2-..../api/loginStatus/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 503.
So this error here, I suggest looking at your headers, and maybe disable some. You currently allow only 2 request headers that might cause some issues as well?
Flask-CORS
A Flask extension for handling Cross Origin Resource Sharing (CORS), making cross-origin AJAX possible.
Installation
Install the extension with using pip, or easy_install.
$ pip install -U flask-cors
Simple Usage
In the simplest case, initialize the Flask-Cors extension with default arguments in order to allow CORS for all domains on all routes. Read More.
from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app)
#app.route("/")
def helloWorld():
return "Hello, cross-origin-world!"
Reference: https://flask-cors.readthedocs.io/en/latest/
Mixed Content: The page at 'https://www.example.com/dashboard' was
loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint
'http://api.example.com/inventory/10/'. This request has been blocked;
the content must be served over HTTPS.
We have this Angular web app that runs with Flask on the back-end.
Everything was working fine until we implemented SSL. Afterwards, we keep getting this strange error everywhere.
Now, the $http.get request in my dashboard.js is definitely calling "https://api.example.com/inventory/10" in the code below and yet the error is claiming that we are trying to request "http" instead.
$http.get($rootScope.baseUrl+'/inventory/' + item.id)
where rootScope.baseUrl is "https://api.example.com".
It's really weird because some GET requests ARE going through from our web application to our back-end, but some requests are throwing this weird error.
Here's the header that gets an error in our Network tab of the console in chrome.
Request URL:https://api.example.com/inventory/10 Request Headers
Provisional headers are shown Accept:application/json, text/plain, /
Origin:https://www.example.com
Referer:https://www.example.com/dashboard
It was a weird case that came down to removing a forward slash from the end of a URL fixing everything. Somehow, whenever we made a GET request using $http in Angular like baseurl + inventory.id + "/", it would make a http request but as soon as remove that slash, it would make the https request correctly.
Still so confused
I think the root of the problem is in server redirects. I was able to resolve same issue with SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') setting for Django (its running behind AWS balancer). Here is documentation.