Cross Domain Image upload Angular+laravel - angularjs

I have been struggling with image upload on server. I am using ngFileUpload on front end. But I always get
"Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource"
Angular Code for file Upload :
var uploadFile = function (file) {
if (file) {
if (!file.$error) {
Upload.upload({
url: baseUrl+'upload',
file: file
}).progress(function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
//console.log(evt.total);
}).success(function (data, status, headers, config) {
$timeout(function() {
console.log(data);
console.log(status);
if(status==200)
{
logo_path = data.logo_path;
}
});
});
}
}
};
On Laravel i have configured CORS like this :
public function handle($request, Closure $next)
{
header("Access-Control-Allow-Origin: http://localhost:8001/");
// ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
];
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;
}
The Normal cross domain POST request works fine. i.e $http.post(). I have tried many different variations of headers on angular but none helps. Also the OPTIONS request returns 200 OK but still preflight response failure message is displayed. Can anyone help me with how to further debug this issue?

Try adding:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, Content-Type');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
in bootstrap/app.php
You may also insert any other header you may need for access control here.

Related

angularjs $http.get not working on mobile browsers

I tried to use this code:
var url = "http://www.test.com?param=1&callback=JSON_CALLBACK";
$http.get(url).success(function(data, status, headers, config) {
if (data.success == 1) {
//do somethings
} else {
//notice
}
});
It is working fine with browsers of laptop but on mobile browsers, it is not working.
in .htaccess, i added:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
Please help!
The mobile browser and desktop browser works same way for http calls. You can make an error block in your code to see what error is coming from the server. Below piece of code is what I am suggesting.
this._getAll = function (model) {
var deferred = $q.defer();
$http
.get("your-secure-rest-url")
.success(function (data) {
deferred.resolve(data);
})
.error(function (reason) {
deferred.reject(reason);
});
return deferred.promise;
};
As you are allowing Access origin "*" for all domain, there is no problem in client side but you need to check the rest server if it is accessable from all domain or is it restricted to particular domain.

REST API error "CORS preflight channel did not succeed"

I created a RESTapi to insert data into my databse, It's working perfectly on POSTMAN extension, but I'm getting an error on angularjs http post method.
My Restapi code is created in yii2 framework. My code is below,
public function actionNew()
{
$model = new Apieducation();
$user_id = $_REQUEST['user_id'];
$education = $_REQUEST['education'];
$passing_year = $_REQUEST['passing_year'];
$institute = $_REQUEST['institute'];
//$model->attributes=$params;
$model->user_id = $user_id;
$model->education = $education;
$model->passing_year = $passing_year;
$model->institute = $institute;
if ($model->save()) {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With,content-type");
echo json_encode(array('status'=>'1','data'=>$model->attributes),JSON_PRETTY_PRINT);
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
}
else
{
$jobs[] = 'failed';
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With,content-type");
echo json_encode(array('status'=>'1','data'=>array_filter($jobs)),JSON_PRETTY_PRINT);
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
}
}
And My Angularjs function code is,
$scope.educationcreate = function() {
var data = $.param({
user_id: $scope.data.user_id,
education: $scope.data.education,
passing_year: $scope.data.passing_year,
institute: $scope.data.institute
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
};
$http.post('http://localhost/basic/web/index.php?r=apieducation/new', data, config)
.success(function(data, status, headers, config) {
alert('Successfully');
})
.error(function(data, status, headers, config) {
alert("ERROR");
});
};
I got console error,
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
http://localhost/basic/web/index.php?r=apieducation/new. (Reason: CORS
preflight channel did not succeed).
How can I solve it?
Using the Cors filter to solve this error,
public function behaviors()
{
return [
'corsFilter' => [
'class' => Cors::className(),
'cors' => [
// restrict access to
'Origin' => ['*'],
'Access-Control-Request-Method' => ['POST', 'GET'],
// Allow only POST and PUT methods
'Access-Control-Request-Headers' => [' X-Requested-With'],
// Allow only headers 'X-Wsse'
'Access-Control-Allow-Credentials' => true,
// Allow OPTIONS caching
'Access-Control-Max-Age' => 3600,
// Allow the X-Pagination-Current-Page header to be exposed to the browser.
'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
],
],
];
}
My short solution:
On server side:
npm install cors
add app.use(cors({origin: '*'})); before all route definitions
On client side:
do everything normally
$http.get('http://localhost:36912/api/permissions').then(function (response) {
console.log(response);
})
.catch(function (error) {
console.error('Status code: ' + error.status);
console.error('Error message: ' + error.data);
});

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

Angular JS : No 'Access-Control-Allow-Origin' header is present on the requested resource

I am trying to create a webservice. I am using AngularJS in client side and Java for webservice. This is my client side code
var url = 'http://localhost:8010/something';
var data = {
"departmentID":$scope.departmentID ,
"departmentName":$scope.departmentName,
};
var config = {
headers: {
'Content-Type': 'Application/JSON',
},
withCredentials : true
};
$http.put(url,data).success(
function(data, status, headers, config){
alert("success :"+data);
}).error(
function(data, status, headers, config){
alert("Failure :"+data);
}
);
This is my server side code
#PUT
#Consumes(MediaType.APPLICATION_JSON)
public Response add(final Department department) {
try {
DepartmentRelation.addDepartment(department);
return Response.status(Status.OK).header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT").header("Access-Control-Allow-Credentials",true).build();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
return Response.status(Status.INTERNAL_SERVER_ERROR).header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT").build();
} catch (SQLException e) {
e.printStackTrace();
return Response.status(Status.BAD_REQUEST).header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT").build();
}
}
But I am getting this error - "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access." While I try using it.
The browser will do a preflight request using the OPTIONS method to check access to the resource. You need to implement a method in your JAX-RS backend responding to OPTIONS requests with CORS headers (as you already do in the "add" method).
#OPTIONS
public Response options() {
return Response
.status(Response.Status.OK)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.header("Access-Control-Allow-Credentials",true)
.build();
}

CORS with Laravel 4 and external Angular

I am noob laravel and angular user. I have wrote very simple api a couple of day ago for learning how does work api. Now i am trying to reach it from another location with very simple angular script. This is my internal domain addres that i'm using instead of localhost/../.. : http://3burcak.dev/api/v1/kategori and this is the index method of kategori controller:
public function index()
{
$cat = EmlakKategori::all();
return Response::json(array(
'cat' => $cat->toArray(),
));
}
So, it is very simple.
When i try to reach it via my very simple angular js, i get OPTIONS 404 not found error if i don't use headers for cors. But if i use those headers inside of filters.php i get OPTIONS 500 Internal Server error.
App::before(function($request)
{
if($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
$statusCode = 204;
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers' => 'Origin, Content-Type, Accept, Authorization, X-Requested-With',
'Access-Control-Allow-Credentials' => 'true'
];
return Response::make(null, $statusCode, $headers);});
App::after(function($request, $response)
{
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
$response->headers->set('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Requested-With');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
return $response;
});
Both situation, i see my json data in Response tab of Firebug... Here is the caps;
Screenshot
And here is my very simple angular
function getKat($http, $scope)
{
$http({
method: 'json',
url: 'http://3burcak.dev/api/v1/kategori'
})
.success(function(data){
$scope.items = data.cat;
})
.error(function(data) {
console.log('error');
});
}
I couldn't solve this problem.
Thanks for help.
I have solved,
I changed angular's method from json to GET and finally it works.

Resources