Not able to call servlet using ajax - java

I am trying to call servlet using ajax on click event. And from that servlet I am calling google auth end point. I tried set header to the servlet I am calling but I an not able to get rid of this error
XMLHttpRequest cannot load
https://accounts.google.com/o/oauth2/auth?client_id=2536-a…nid%20profile%20email&state=F1BFD3804&display=popup.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8080' is therefore not allowed
access.
Here is the code
$.ajax({
type: "GET",
url: "/url-for-servlet",
dataType: "jsonp",
contentType: 'application/json',
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR)
},
success: function (data) {
alert("yippy");
console.log(data);
}
});
On servlet I added to response
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.addHeader("Access-Control-Max-Age", "3600");
response.addHeader("Access-Control-Allow-Headers", "x-requested-with");
Any idea what I am missing here? Thanks for the help.

This is a standard security restriction : JS cannot make requests to domains other than their own. So you have an application on localhost making Ajax calls to an application on accounts.google.com - not allowed by default.
See this question

AJAX usually doesn't allow to call other domain API from it. It is called CSRF attack. The solution for you is, Post the data to your server servlet and do the action required there in the backend(Servlet).

Related

No 'Access-Control-Allow-Origin' is present on requested resource

I am having a weird issue where my client side request is telling me I have no 'Access-Control-Allow-Origin' present when making an HTTP POST request to a java servlet I have hosted and live. I have made sure to add the necessary headers in my response to clear up CORS requests issues but it does not seem to be recognizing the headers.
Here is my angular $http.post request I am making from the client side:
var parameter = JSON.stringify(details);
var req = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
data: parameter
}
$http.post(localurl, req).
then(function(response) {
});
Here is the error I am getting from chrome:
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:8081' is therefore not allowed access.
Here is the beginning of my java servlet doPost function:
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res) {
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
res.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
I have been searching various stackoverflow questions and those response headers I am setting in my servlet should clear up the CORS requests issues but it does not seem to be recognizing the response headers I am setting at the beginning of the doPost function. Any and all help is very appreciated. Thanks in advance.
The problem is on your back-end, if yours is nodejs, should be like this way to allow Access-Control-Allow-Origin:
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});

How to call an AXIS web service via AJAX?

I'm very new to web services. I used eclipse and some tutorials from the web to create a simple web service called DeScriptor which I uploaded to a Tomcat server. It's accessible through this URL
http://www.xwizard.de:8080/services/DeScriptor
and according to the message written out there, it appears to be working (right?).
So far, so good, but now I don't know how to call it. The service has a single method String retrieveSVGFromScript(String scrp) which I tried to call with this AJAX code:
var hallowelt = "Hallo Welt";
var params = JSON.stringify({scrp: hallowelt});
$.ajax({
type: "POST",
url: "http://www.xwizard.de:8080/services/DeScriptor/retrieveSVGFromScript",
data: params,
dataType: "json",
contentType: "application/json; charset=utf-8",
crossDomain: true,
success: function (msg) {
console.log(msg.d);
},
error: function (xhr, status, error) {
// Some error handling.
}
});
hoping that I'd get the result string of the method by msg.d, but instead I got this not so informative error message:
jquery.js:8630 POST http://www.xwizard.de:8080/services/DeScriptor/retrieveSVGFromScript 500 (Internal Server Error)
Can somebody point me in the right direction?
EDIT: You can find the WSDL here: http://www.xwizard.de:8080/services/DeScriptor?wsdl
You are trying to call a server webservice using REST style (i.e. setting content-type, providing params as JSON message, etc.).
But the webservice expects a SOAP message. An example how to send a SOAP message with Javascript can be found here.

How to consume rest web service from ajax call

I want to call my rest web service from ajax. Url for my service is 'https://scv-dev.com/cdcAug/surveys/surveyData'. Iam able to call this service from rest client (firefox browser) but when am trying to call from ajax am getting error.
Ajax call :
$.ajax({
type: "POST",
url: "https://scv-dev.com/cdcAug/surveys/surveyData",
data: JSON.stringify({surveyId:1}),
dataType: "json",
headers: {
Accept: "application/json",
"Access-Control-Allow-Origin": "*"
},
success: function (data) {
alert(1);
},
error: function (jqXHR) {
alert(2);
}
});
Below is code for webs service :
#RequestMapping(value = "/surveyData", method = RequestMethod.POST, headers = "Accept=application/json")
public #ResponseBody
SurveyDataResponse getSurveyData(#RequestBody SurveyResApp surveyResApp,
final HttpServletResponse httpResponse) {
..............
}
You appear to be confused about Access-Control-Allow-Origin: *. That is something the server returns, not something the client sets.
It appears that you have a same-origin access error and looking in the browser error log or diagnosing the returned error codes should tell you what exactly is going on.
You probably need to enable your web service for cross origin access by adding that header Access-Control-Allow-Origin: * to your server response. See here for an example.
I created filter class added below code in that to add "Access-Control-Allow-Methods" in response.
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
response.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
response.addHeader("Access-Control-Max-Age", "1728000");

webservice call using Post

I am new to webservice and ajax .. I tried to call a webservice using POST method.
I tried to invoke it using Postman (Google chrome App) and I was getting the response but when I tried using Ajax I am getting error
Following are the things I did:
My Code: (I wrote a JS in which I included following code and tried all the commented options too ):
$.ajax({
crossDomain: true,
url : 'https://yxyxyxyxyx/search/v1/query.json',
type : 'POST',
dataType : "json",
data: {appId: "a9b475a079",query: "dhcp"},
//async : true,
//headers: {"Content-type": "application/json"},
headers: { 'Access-Control-Allow-Origin': '*' },
//contentType: "application/json; charset=utf-8",
//headers: ('Access-Control-Allow-Methods: GET, POST, OPTIONS'),
//headers: ('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With'),
//headers: ('Access-Control-Allow-Credentials: true'),
// Access-Control-Allow-Origin: "http://localhost:8080",
// headers: { 'Access-Control-Allow-Origin': '*' },
//userAgent : 'Mozilla/22.0',
success: function(data){
alert("hi success");
},
error: function(data) {alert("An error occured: " + data.status + " " + data.statusText);
});
I am getting the alert in the error and getting following error while debugging:
XMLHttpRequest cannot load https://www.sample.search/v1/query.json. The request was redirected to 'https://www.sample/obrareq.cgi?wh%3DCCI-STG4%20wu%3D%2Fuesps%…n-tools-stage.cisco.com%20ru%3D%252Fuesps%252Fsearch%252Fv1%252Fquery.json', which is disallowed for cross-origin requests that require preflight.
I tried all the options to resolve the CROS option in which I found on net… do we have any other way to resolve it.
Can someone help me if we can do it using a java class that will also serve the purpose

How To Overcome CORS Issue From Angular JS

I got stuck at one point while calling REST service from my Angular JS code :
Service:
app.factory('UserFactory', function ($resource) {
return $resource('http://localhost:8080/demoApp/service/users', {}, {
show: { method: 'GET', isArray: true },
})
});
Controller:
function userListController($scope, UserFactory){
$scope.showUser = function () {
alert("Show user ...");
$scope.fetchedData = [];
$scope.users = UserFactory.show();
$scope.fetchedData.push($scope.users);
};
}
In order to overcome the CORS we have implemented Java CORS Filter as below -
Following line were written in doFilter method inside a Filter -
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
It is working perfect with $http.jsonp. But while we are calling with above way we got following error in Javascript console of the browser (Chrome) :
XMLHttpRequest cannot load http://localhost:8080/demoApp/service/users. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin http://localhost:63342 is therefore not allowed access.
Please help me ...
Regards,
Jayanta P.
Very helpful. This excerpt:
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
worked very well; however, I had to disable the security flag of my Chrome browser by using the CORS plug-in available in Chrome. After that, I was able to make restful call from my angularjs app seamlessly.
Have you tried something like this?
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);

Categories