How To Overcome CORS Issue From Angular JS - java

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'];
}
]);

Related

Why Cookies are not set in the browser but works in Postman?

Backend is Spring boots. I setup cookie there and it is working fine with postman.
#CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")
//Spring boots (http://localhost:8080)
Cookie cookie = new Cookie("access-token",token);
cookie.setPath("/");
cookie.setSecure(false);
response.addCookie(cookie);
response.addHeader("Access-Control-Allow-Credentials", "true");
Front End is ReactJS, I've used a POST method using Axios to get Login information.
I am getting response, but cookies are not set.
//React JS (http://localhost:3000)
axios({
url: common.url + '/login',
data: "userId=" + userid+ "&password=" + password,
method: 'post',
cache: false,
contentType: 'application/x-www-form-urlencoded',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', 'Cache-Control': 'no-cache','withCredentials':'true'
}
}).then(function (result) {
;
//Success Login
})
Tried many things. No Luck
You need some more setup on the Cookie for it to work as what you expect
cookie.setPath("/") if you want it to be included in any requests.
If you are running your application in a non-https mode, you need to cookie.setSecure(false), otherwise, the browser will just ignore it.
If you want the cookie to be httpOnly, do cookie.setHttpOnly(true)
There're plenty more setups but those three should give you a decent result
Got a fix finally.
axios.post(url+'/login', { json }, { withCredentials: true }).then(function (result) {
}
WithCredentials should be passed like this from front-end.
in Backend code, along with the Crossorigin management, we need to add allowCredentials to true

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();
});

Not able to call servlet using ajax

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).

No 'Access-Control-Allow-Origin' header is present on the requested resource in angularjs and codeigniter

I have an angularjs app, and codeigniter as the backend and XAMPP as the server. The app is working fine when I run it with my own PC. Now my problem is if I run the app with other computer which has the same network through accessing the ip address in a web browser it has an error like this:
XMLHttpRequest cannot load http://localhost/j3safetysolutions/index.php/signin?username=hello&password=world. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.18' is therefore not allowed access. The response had HTTP status code 404.
But when I try to access the API (http://localhost/j3safetysolutions/index.php/signin?username=hello&password=world) using a web browser in different computer it works fine. I already enabled CORS in my codeigniter PHP script. To properly illustrate my problem here are the source codes:
My PHP script I added to the function construct:
function __construct() {
parent::__construct();
$this->load->model('user','',TRUE);
$this->load->helper('url');
//enabling CORS
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if($method == "OPTIONS") {
exit();
}
}
My angularjs script when I clicked the button the app will send a request to the server using the IP address:
angular.module('j3appApp').controller('signin', ['$scope', '$http', '$location', function($scope, $http, $location){
$scope.signin = function() { //the button is clicked
if ($scope.uname != null && $scope.pword != null) {
$http.get("http://localhost/j3safetysolutions/index.php/signin?username=" + $scope.uname + "&password=" + $scope.pword).success(function(response) {
if (response.returnValue == 'FAILED') {
alert(response.returnMessage);
}
else {
document.cookie="username=" + response.username + "; path=/";
window.location = "#/home";
}
}).error(function(response){
alert('An error occured. The server is not responding to the sent request. Please contact the system administrator. Error detail: ' + response);
});
}
}
}]);
I know that there are too many questions like this but none of the answer of them is working for me. Any idea of yours is very very useful for me.
I had a similar issue, looks like you may have the headers after the output.
"that header() must be called before any actual output is sent"
reference: http://php.net/manual/en/function.header.php

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");

Categories