angular POST request not working but GET working fine - angularjs

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

Related

angular $http request from 80 port to another port

I am trying to hit a node api with port 3000 on local server from a angular 1 project using $http method but I am getting this error:
XMLHttpRequest cannot load http://localhost:3000/login. Request header
field Authorization is not allowed by Access-Control-Allow-Headers in
preflight response.
I also added the Access-Control-Allow-Origin : * in node js as :
req.on('end', function() {
req.rawBody = req.rawBody.toString('utf8');
res.setHeader('Access-Control-Allow-Origin', 'http://localhost');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', '*');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', '*');
// 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', false);
next();
});
And my angular code is :
var req = {
method: 'POST',
url: 'http://localhost:3000/login',
headers: {
'Content-Type': 'application/json',
// 'cache-control': 'no-cache'
},
data: { username: username, password: password },
json: true
};
$http(req).then(function successCallback(response){
console.log(response);
}, function errorCallback(response){
console.log("Error : ");
console.log(response);
});
But still I am getting this error.
The error is in the preflight response as specified.
So you need to handle the OPTIONS method :
req.on('end', function() {
req.rawBody = req.rawBody.toString('utf8');
res.setHeader('Access-Control-Allow-Origin', 'http://localhost');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', '*');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', '*');
// 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', false);
if (req.method === "OPTIONS") {
return res.status(200).end();
}
return next();
});
This is due to the way browsers handle cross-origin request. An OPTIONS request (preflight) is sent before your POST to get allowed origins, headers and methods.

CORS Issue in Web Console (angular js)

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

Ionic http post to external url

Im trying to send a post to a url with Ionic using angular, but i have the response:
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:8100' is therefore not allowed access. The response had HTTP status code 404.
I know that the external service is working, because i tested it by ajax and everything works perfectly...
Below the code used in AngularJS (Ionic) and Ajax:
Ionic:
var loginServiceUrl = 'http://url.com.br'; //It is not the real one
var loginServiceData = {
email: email#email.com.br
senha: 1234
};
$http.post(loginServiceUrl, loginServiceData).
then(function (res){
console.log(res);
});
Ajax:
$.ajax({
type: "POST",
url : 'http://url.com.br', //It is not the real one
data : {email: 'email#email.com.br', senha: '1234'},
success: function(result) {
$('html').text(JSON.stringify(result));
}
});
Does anyone know why I get the post via ajax on my localhost and not with the ionic, also localhost?
Check this out. It is well explained how to handle issues like yours --> http://blog.ionic.io/handling-cors-issues-in-ionic/
Try to add headers in your POST request.
//example of DataToSend
var DataToSend = {
userID: deviceID,
coordLat : pos.coords.latitude,
coordLon: pos.coords.longitude
};
$http({
method: 'POST',
url: 'http://url.com.br',
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
data: DataToSend
})
CORS has nothing to do with your frontend.
Before sending the POST request, browser send a OPTIONS request to the server to check if call from your domain is allowed or not.
Since, you are getting Status 404, that means your server is not handling the OPTIONS request
1. Allow the OPTIONS request (same as POST)
Now come to second part i.e " Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' "
After allowing the OPTIONS request, now set the response header of OPTIONS request (Browser will check the response of OPTIONS request and then process the POST request only if there is 'Access-Control-Allow-Origin' present in the OPTIONS response.
2. Set the response headers of OPTIONS request
response().setHeader("Access-Control-Allow-Origin", "*");
response().setHeader("Allow", "*");
response().setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
response().setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent");
Example..
(In Java)
Router:
OPTIONS /*all
controllers.Application.preflight(all)
Controller Function:
public static Result preflight(String all) {
response().setHeader("Access-Control-Allow-Origin", "*");
response().setHeader("Allow", "*");
response().setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
response().setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent, Auth-Token");
return ok();
}
Hope this will solve your problem.
Cheers

Cross Domain Image upload Angular+laravel

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.

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