CORS Issue in Web Console (angular js) - angularjs

I have a developed a web console in angular JS in which I am using post and put methods and making HTTP requests in which I send json and calling a WSO2 REST API to get response accordingly. Its running on server but I am facing CORS problem. I have add add extension in browser and enable it otherwise I get following error.
XMLHttpRequest cannot load http://127.197.200.100:8000/ManagementAPI/createuser. 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.197.200.100:8000' is therefore not allowed access.
This is how I am sending request
CreateUser: function(adata) {
var config = {
headers :{
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}
var promise = $http.post(213.187.243.177:8283/ManagementAPI/createuser,adata,config).then(function (response) {
return [response.status,response.data];
},function (response) {
console.log("Error Returned" + response.status);
return [response.status,response.data];
});
return promise;
},
I have tried ThisLink for solution but did not work. Need a solution for accessing it without CORS.

Set headers in back end for avoiding CORS issues .
Sample code in php is shown in below
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}

Related

Request Forbidden 403 when request made to Square-Connect from localhost

I am trying to make a request to 'https://connect.squareup.com/v2/locations' using angularjs, where call is getting failed saying 403 FORBIDDEN.
Here is the code sample :
var url = 'https://connect.squareup.com/v2/locations';
var config = {
headers: {
'Authorization': 'Bearer sandbox-sq0atb-JJGltCa375qzAyoQbjPgmg',
'Accept': 'application/json',
"X-Testing": "testing"
}
};
$http.get(url, config)
.then(
function (response) {
console.dir(response);
},
function (response) {
console.log("failed" + response)
}
);
I have made a fiddle of the above sample. Any help is appreciated.
http://jsfiddle.net/dx6tdrha/
Are you seeing this error: XMLHttpRequest cannot load https://connect.squareup.com/v2/locations. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.? It means that you cannot access the API via front-end Javascript (like AngularJS) You'll need to use a different implementation like Node.js, PHP, etc.

Ajax Post to Web Api (405 Method Not Allowed)

Having an issue when I am posting AngularJS data to Web API end point. From the client browser I receive:
405 (Method Not Allowed)
Response for preflight has invalid HTTP status code 405
I have two separate projects which both run in localhost. On my Web Api I have set EnableCors() on config.
If I set content-type of the header to:
'Content-type': 'application/x-www-form-urlencoded; charset=utf-8'
Then it's able to hit my Web API endpoint. However my object argument is null. Could this be XML format rather than JSON? How do I go about resolving this?
Client side code:
function signUp(data) {
$http({
method: 'POST',
url: 'http://localhost:15218/api/account/register',
data: JSON.stringify(data),
headers: {
'Content-type': 'application/json'
}
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
});
}
}
Server Side Method signature:
[HttpPost]
[Route("Register")]
public async Task<HttpResponseMessage> Register(UserCommand command)
You can enable cors on the service by adding global.asax file
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
Response for preflight has invalid HTTP status code 405
Before making the POST request you want to make, the browser is making an OPTIONS request asking for permission.
The server is responding to the OPTIONS request without a 200 response. The error message tells you that explicitly. (Maybe Access-Control-Allow-Origin cause the problem)
So before anything else, you must check for type of request method. If it is OPTIONS , pass 200 response code.

angular POST request not working but GET working fine

I know this has been asked, but I tried a lot of things and could not make this work.
I am making GET and POST request from my angular application to laravel backend api's. I am able to fetch json from get request but my POST request fails for json data type. It works for
x-www-form-urlencoded
but I am unable to extract data as it is in json format.
$http.get('http://api.app.mywebsite.com/users').success(function(data){
$scope.user = data;
});
$scope.addUser = function(user){
console.log($scope.user);
$http({
method: 'POST',
url: 'http://api.app.mywebsite.com/users',
dataType: 'json',
data: $scope.user,
headers: {'Content-Type': 'application/json; charset=utf-8' }
}).then(function(result){
console.log(result);
}, function(error){
console.log(error);
})
}
$scope.user is posted on form submit.
The error I get :-
XMLHttpRequest cannot load http://api.app.mywebsite.com/users.
Response to preflight request doesn't pass access control check:
No 'Access-Control- Allow-Origin' header is present on the
requested resource. Origin 'http://app.mybackend.com' is therefore not allowed access.
My CORS.php middleware in laravel :-
public function handle($request, Closure $next)
{
header("Access-Control-Allow-Origin: *");
// ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin, X-Requested-With, Accept'
];
if($request->getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return \Response::make('OK', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
$response->header($key, $value);
return $response;
return $next($request);
}
routes.php
Route::group(['middleware' => 'cors'], function()
{
Route::resource('users', 'UserController');
});
Update:
http://let-aurn.github.io/laravel-5-cors/
You need to configure your http server to allow cors
Similar question:
How to enable CORS in AngularJs
And:
AngularJS performs an OPTIONS HTTP request for a cross-origin resource

CORS error with AngularJS post only in FireFox

I am having issues only with FireFox when making a cross origin request in an Ionic app (so it's using AngularJS). The js app is doing a $http.post() to a Laravel 5.1 API, and I get the following error only in FireFox (39.0.3):
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://blah.dev/endpoint. (Reason: missing token 'content-type' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel).
This is on my localhost (OSX Mavericks). and works fine in Chrome and Safari, only FireFox is given the error. I have cleared the cache, and tried in a "private window", with the same results.
Here is the Laravel route defined to handle the OPTIONS request:
Route::options('endpoint', function() {
return response('OK')
->header('Access-Control-Allow-Headers ', 'Origin, Authorization, X-Requested-With, Content-Type, Accept')
->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
->header('Access-Control-Allow-Origin', '*')
->header('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0')
;
});
Route::post('endpoint', array('uses' => '\Path\To\Controller#endpoint'));
I did find this question that seems to have a similar issue only in FireFox, but the solution was to comma separate the Allow-Methods, which I already am.
The message " missing token 'content-type' " is about the client. For a http request to be a valid post one, it must have a header
'Content-Type': 'application/x-www-form-urlencoded'
or
'Content-Type': 'multipart/form-data'
The first content-type is the most common one.
In angularjs one way to do a CORS post request is
$http.post(
'http://external-domain.ext/the/rest/url',
'param_name=param_value',
{headers:{'Content-Type': 'application/x-www-form-urlencoded'}}
).
then(function successCallback(response) {
$scope.something = response;
}, function errorCallback(response) {
// not good
});
If the server is configured with
header('Access-Control-Allow-Origin', '*'), the CORS post must succeed without authentication and credentials.
on the back end try putting
->header('Access-Control-Allow-Credentials', 'true')
and on the front end try putting
.config(function($locationProvider, $httpProvider) {
// CORS requests with credentials
$httpProvider.defaults.withCredentials = true;
})

AngularJS $http GET method to backend server: Request Method:OPTIONS 405

$http GET request to a clojure backend, to get a list of services.
I get is an OPTIONS request (???), which gets a 405 response...
<code>
var config = {headers: {
'Authorization': 'Bearer d2VudHdvYW5nZV9tZQ',
"X-Testing" : "testing"
}
};
$http.get(SERVER.MESSAGE_SERVICES, config)
.success(function(successCallback) {
$scope.services = successCallback;
})
.error(function(errorCallback) {
console.log(errorCallback.toString);
}).
finally(function() {
console.log("Message services rest call");
});
</code>
**clojure backend**:
<code>
headers {"Access-Control-Allow-Origin" "*"
"Access-Control-Allow-Headers" "X-Requested-With, Origin,Content-Type, Accept"
"Access-Control-Allow-Methods" "GET, POST, OPTIONS"}
</code>
There is no problem that AngularJS sends an OPTIONS request, that is because CORS standards force to do so. Be sure that the server is configured to allow a GET method.
Yes as raso suggested this problem is because of Cross Origin Resource Sharing(CORS). The same old privacy policy prevents JS/ angularJS from making requests across domain boundaries.
Configure server to allow cross domain requests.
Or
If you are using Chrome than you can use this extension to surpass this problem.

Resources