Using angularjs to request elasticsearch as cross domain - angularjs

I am making a web app using angularjs. I am making request on elasticsearch api. This is the code:
app.controller('usersDatas', function($scope, $http){
$http.post("http://192.168.6.55:9200/userdata/_search", {headers : { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
data: "{ 'query': { 'query_string': { 'query': 'png' } } }"
// Access-Control-Allow-Origin: true
}).success(function(data){
console.log(data);
});
});
This is error I have :
XMLHttpRequest cannot load http://192.168.6.55:9200/userdata/_search. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.
I have added this :
http.cors:
enable: true
allow-origin: /https?:/\/\/localhost(:[0-9]+)?/
to my elasticsearch (/etc/elasticsearch/elasticesarch.yml) config. I don't know if the problem comes from elasticsearch or from angularjs.
How can I solve this ?
Thanks.

You must add in HEADER Access-Control-Allow-Origin
PHP Example:
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

This is browser issue First close all the chrome browser windows ...
open terminal
sudo -i
(Your Password)
then type
google-chrome --disable-web--security
Then try the link in that url

Related

Ajax call error during Rally sdk custom dashboard developement

I'm getting 403 exception when I make an ajax call to jenkins api call to get the build details from Rally sdk custom html interface.
//Ajax api call to jenkins
var blink ="https://[jenkinshost]/job/Appdev/job/TestProject/api/json";
Ext.Ajax.request({
url: blink,
method :'GET',
crossDomain: true,
withCredentials: true,
headers : {
'Authorization': 'Basic dsasfsfxfhfj',
'Content-Type': 'application/json;charset=UTF-8',
},
success: function(response){
var backToJs=JSON.parse(response.responseText);
console.log('resp data-',backToJs);
//console.log(backToJs['QueryResult'].Results);
},
failure: function(response) {
console.log('jenkins-ajax call failure');
}
});
ajax call error-
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://rally1.rallydev.com' is therefore not
allowed access. The response had HTTP status code 403.
Add to your .htaccess file on both domains this string:
Header add Access-Control-Allow-Origin "*"
And try to find more information about cross-domain requests.

AngularJS send request x-www-form-urlencoded

I have a Django server amd I am trying to send a request to it using AngularJS.
This is my code:
var req = {
method: 'POST',
url: 'http://127.0.0.1:8000/api/user/register/',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/x-www-form-urlencoded'
},
data: $.param({ phone_number: phonenumber, password: phonenumber, country: 1 })
}
$http(req).then(function(response){
callback(response);
}, function(response){
console.log(response);
});
I am getting the following error:
XMLHttpRequest cannot load http://127.0.0.1:8000/api/user/register/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1' is therefore not allowed access.
I am not sure what can be the problem here. I already created an applications for iOS and Android that both communicate with the same server and I didn't have any problems.
I am using AngularJS 1.5.5 https://code.angularjs.org/1.5.5/
Can someone suggests what is wrong with this request in AngularJS?
It appears that the code didn't need this part:
'Access-Control-Allow-Origin': '*',
The real problem was because the server wasn't allowing local urls.

$http header 'Content-Type' not appending in the header - AngularJS

I'm using $http to do a GET request and I wanted to append 'Content-Type': 'application/json' in the header. If I don't append this header 415 (Unsupported Media Type) error is thrown.
I'm using Apache 2.2.13 with ProxyPass, in which I DO NOT say
RequestHeader append Content-Type "application/json". However if I put the RequestHeader configuration in apache $http.get works fine and the 'Content-Type' is also appended.
Scenario 1 :
Using $http, trying GET request
Request :
$http({
method: 'GET',
headers: { 'Content-type': 'application/json'},
url: '/items/?customerId=5656'
});
Chrome Network Tab :
Scenario 2 :
Using Restangular, trying the same GET request
Request :
Restangular.setDefaultHeaders({'Content-Type': 'application/json'})
Restangular.setBaseUrl('/items')
Restangular.all('').getList({customerId: '103020'}, {'Content-Type': 'application/json'});
Chrome Network Tab :
The other interesting part here is, when I do some mistakes on the Request Header like,
Restangular.setDefaultHeaders({'Contentttt-Type': 'application/json'})
and try Scenario 1, I notice the following in the Chrome Network Tab.
Scenario 3 :
Using jQuery ajax, trying the same GET request
Request :
$.ajax({
url: "/items/?customerId=103020",
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('Content-Type', 'application/json');},
success: function() { alert('Success!'); }
});
Chrome Network Tab :
Questions :
Is it necessary to add RequestHeader append Content-Type "application/json" in Apache configuration? But if I add that I get 415 errors on POST requests.
What is the problem with AngularJS and Restangular that it won't append Content-Type headers to its network calls on GET?
What is the best solution to solve this? I have tried out all the combinations but no luck!
Versions :
Angular : 1.2.22
Restangular : 1.4.0
On the one hand, with the $http service, you can override or add your headers using $httpProvider when calling the config method on your module :
module.config(function($http) {
$httpProvider.defaults.headers.get = { 'Content-Type : 'application/json' };
});
On the other hand, with the GET method, if your API is really RESTFull, only the Accept header should be set since you are not sending JSONdata.
Thus, use the above code for your PUT/POST methods and force the Accept header for the GETmethod:
module.config(function($http) {
$httpProvider.defaults.headers.post = { 'Content-Type : 'application/json'};
$httpProvider.defaults.headers.put = { 'Content-Type : 'application/json'};
$httpProvider.defaults.headers.get = { 'Accept : 'application/json'};
});
EDIT 1:
If you want to force the content-type in a GET request, you have to add a blank data :
$http({
method: 'GET',
data:'',
dataType:'json',
headers: { 'Content-type': 'application/json'},
url: '/items/?customerId=5656'
});
Setting a Content-Type header field on an HTTP request that doesn't have a request body (such as GET) is non-sense.
Maybe what you really want is set "Accept"?

Call symfony 2 rest api with Angular JS, cors

I'm using angularJS to call a restfull API in symfony 2.
My angularJS app url is angular.me.dev
My symfony2 api url is api.me.dev
I followed this tutorial to make my restfull api.
The problem is when I try to call this api
$http.({
method: 'GET',
url: 'http://api.me.dev/api/articles',
headers: {
'Authorization': 'Bearer ' + token
}
})
An error occured: (here on google chrome):
XMLHttpRequest cannot load http://api.me.dev/api/articles. Response for preflight has invalid HTTP status code 405
(and on on firefox):
The Same Origin Policy disallows reading the remote resource
what did I find about this ?
AngularJS Sends OPTIONS request instead of POST
AngularJS performs an OPTIONS HTTP request for a cross-origin resource
Then I decide to allow headers, origin, ... on my server like this:
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Credentials "true"
Header always set Access-Control-Allow-Methods "PUT, DELETE, POST, GET, OPTIONS"
Header always set Access-Control-Allow-Headers "*"
No change
I add to AngularJS
#coffee script
app.config ['$httpProvider', ($httpProvider) ->
$httpProvider.defaults.useXDomain = true
delete $httpProvider.defaults.headers.common['X-Requested-With']
]
Then I decided to install NelmioCorsBundle in my symfony api but I didn't see any change.
Finally, I notice a call works
$http.({
method: 'GET',
url: 'http://api.me.dev/api/articles',
})
Here the call return a 401 response (good, i need to be logged)
$http.({
method: 'GET',
url: 'http://api.me.dev/public/api/users',
})
Here I have a call doesn't need authorization, it works.
I found only when I remove headers it works, and when I had any headers (content-type or authorization for example) an error occured.
Can anyone help me ? thanks !
Ok, my bad.
I said NelmioCors seems not working but i did something wrong.
I try again with nelmio cors bundle, using this configuration.
nelmio_cors:
paths:
'^/':
allow_origin: ['http://angular.me.dev']
allow_headers: ['Authorization', 'X-Requested-With', 'Content-Type', 'Accept', 'Origin', 'X-Custom-Auth']
allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTIONS']
max_age: 3600
It's working !
NelmioCorsBundle resolve the problem.
https://github.com/nelmio/NelmioCorsBundle

AngularJS POST fails with No 'Access-Control-Allow-Origin' when using data payload object but works using query params like payload

I am facing a weird issue. I am running my angularjs app in nodejs server locally which calls a POST API from my app located on Google App Engine. The API is configured with all CORS headers required as follows:
def post(self):
self.response.headers.add_header("Access-Control-Allow-Origin", "*")
self.response.headers.add_header("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTIONS")
self.response.headers.add_header("Access-Control-Allow-Headers", "X-Requested-With, content-type, accept, myapp-domain")
self.response.headers["Content-Type"] = “application/json; charset=utf-8”
GET requests to the API work without issues.
POST requests to the API work but ONLY when I send the post data as a 'string of params' and NOT when post data is sent as an object which is the right way to do. Eventually I need to be able to upload pictures using this API so the first solution below might not work for me. Please help!
METHOD 1: This works:
postMessageAPI = "https://myapp-qa.appspot.com/message";
var postData = "conversationid=1c34b4f2&userid=67e80bf6&content='Hello champs! - Web App'";
var postConfig = {
headers: {
"MYAPP-DOMAIN" : "myapp.bz",
'Content-Type': 'application/json; charset=UTF-8'
}
};
$http.post(postMessageAPI, postData, postConfig).
success(function(data){
$log.log("POST Message API success");
}).
error(function(data, status) {
$log.error("POST Message API FAILED. Status: "+status);
$log.error(JSON.stringify(postData));
});
METHOD 2: This fails:
postMessageAPI = "https://myapp-qa.appspot.com/message";
var postData = ({
'conversationid' : '1c34b4f2',
'userid' : '67e80bf6',
'content' : 'Hello champs! - Web App'
});
var postConfig = {
headers: {
"MYAPP-DOMAIN" : "myapp.bz"
'Content-Type': 'application/json; charset=UTF-8'
}
};
$http.post(postMessageAPI, postData, postConfig).
success(function(data){
$log.log("POST Message API success");
}).
error(function(data, status) {
$log.error("POST Message API FAILED. Status: "+status);
$log.error(JSON.stringify(postData));
});
When I use METHOD 2 it fails with the following error in the console:
XMLHttpRequest cannot load https://myapp-qa.appspot.com/message.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://0.0.0.0:8000' is therefore not allowed access.
Please let me know if you have any solution. Thanks in advance.
The issue is most likely with Angular sending a pre-flight OPTIONS request to check the access headers from the server. I am not sure how OPTIONS requests are handled in your API, but I am betting these headers are not being added. I suggest installing Fiddler to monitor the actual requests to see what is going on with the headers. You may only be adding them to your POST responses.
See this answer for details on why METHOD 1 may work in this scenario, while METHOD 2 does not.
Here are some more details about pre-flight requests.

Resources