angular laravel nginx 400 Bad Request - angularjs

Help, I've got 400 error on POST and or PUT method, but GET works just fine,
I'm using angular as front end and laravel as API, my server is using nginx,
I've used CORS and I everything works fine on my local vagrant which is running on apache.
I'm sure I have my route set correctly, here's some of it from the module I use:
Route::group(array('prefix'=>'/api', 'middleware' => 'cors'),function(){
Route::post('/create_level', 'LevelController#store');
Route::get('/read_level', 'LevelController#index');
Route::get('/read_level/{id}', 'LevelController#show');
Route::put('/read_level/{id}', 'LevelController#update');
Route::delete('/read_level/{id}', 'LevelController#destroy');
here's part of my angular service:
app.service("edulevelService", function ($http, $q, $rootScope)
{
edu.updateEdulevel = function(id, edu){
var deferred = $q.defer();
$http.put($rootScope.endPoint + 'read_level/'+ id, edu)
.success(function(res)
{
deferred.resolve(res);
})
.error(function(err, stat){
deferred.reject(err);
console.log('error code: Ser-UEDU');
});
return deferred.promise;
}
edu.createEdulevel = function(edu){
var deferred = $q.defer();
$http.post($rootScope.endPoint + 'create_level', edu)
.success(function(res)
{
deferred.resolve(res);
})
.error(function(err, stat){
deferred.reject(err);
console.log('error code: Ser-CEDU');
});
return deferred.promise;
}
....
oh I forgot to mention different method cause different error code POST cause 405, PUT cause 400, and I've tried using Postman:
POST is working using text type and return 405 using application/json,
but when I tried
PUT method even though it return 200 I only got NULL data entered to my db (text type), and if I use application/json it return 400
Please Help

Finally found solution:
change $http.post to:
$http({
method: "post",
url: $rootScope.endPoint + 'create_level',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({ .... })
})
somehow it works, exept on my login page which using stellizer to do post method and i can't find how should I change it without breaking all the function...
any one?
I only need to add:
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
and
data: $.param({ ...... })

Related

Response is undefined in success $http call angularJS

Although my backend is working correctly and I'm getting correct response from Postman crafted request
I can't see response in my angularJS controller. ( i execute this call inside controller to simplify situation )
$scope.click = function (auction_id) {
$http({
url: baseUrl + 'auctions/' + auction_id +'/followers',
headers: {
'Content-Type' : 'application/vnd.api+json'
},
method: 'POST'
})
.then(function(response) {
console.log(response);
})
.catch(function(response) {
return response;
});
};
I'm passing token with httpInterceptor which is working fine for the rest of my app.
URL is correct because I'm getting valid error number in console:
POST ##################/v1/auctions/172/followers
422 (Unprocessable Entity)
CategoryCtrl.js:64 undefined
64 line is that one console log in success .then(function....
Headers in (which I believe is) response headers from postman tab (third from Body in first screenshot)
Why response is undefined?
*Hashes in url code are mine.
From your REST API request, you're getting response with status 422, that means you've got a client error. Regarding your request, you have to handle a request when error will come. To handle error in asynchronous requests there is a second parameter of .then(mySuccessMethod(), myMethodOnError()) method.
More details about .then() and .catch() methods for promisses.
$scope.click = function (auction_id) {
$http({
url: baseUrl + 'auctions/' + auction_id +'/followers',
headers: {
'Content-Type' : 'application/vnd.api+json'
},
method: 'POST'
})
.then(function(response) {
console.log(response);
}, function(error) {
// Here goes your code to handle an error with status 4XX
console.log(error)
})
.catch(function(response) {
// Catch will come when you throw an error
return response;
});
};
When you made the request in Postman, you pass the token in the Auth attribute of the header in the request. In your code, you did not.

Getting successful result with $.ajax request but Error-500 with $http request

I am working on a small web application which simplifies the process of creating and populating USPTO IDS forms by accessing data from another server. For accessing data I am using this API - http://ops.epo.org/3.1/rest-services/published-data/publication/epodoc/US9623902/biblio.js.
I am doing this with angular and hence I used $http but it is throwing error 500 (Internal Server Error). while doing it with ajax-request, its working fine. In fact any other method like $.get() instead of ajax throwing the same error, even I used ng-resource get method but no help. I am not getting what I am doing wrong.
Here are my codes -
$.get( "http://ops.epo.org/3.1/rest-services/published-data/publication/epodoc/US9623902/biblio.js",
function( data ) {
vm.inventors = data['ops:world-patent-data']['exchange-documents']['exchange-document']['bibliographic-data']['parties']['inventors']['inventor'];
console.log(vm.inventors);
});
var req = {
method: 'GET',
url: 'http://ops.epo.org/3.1/rest-services/published-data/publication/epodoc/US9623902/full-cycle.js',
};
$http(req).then(function(response){
console.log(response);
}, function(response){
console.log(response);
});
Both of these codes are throwing error 500. Here is the image
while this code is working fine. But here I am getting an issue of page load, the page is loaded before data is bound to $scope and hence not showing on the page.
$.ajax({
url: 'http://ops.epo.org/3.1/rest-services/published-data/publication/epodoc/' + 'US9623902' + '/biblio.js',
type: 'GET',
dataType: "jsonP",
success: function(data) {
vm.inventors = data['ops:world-patent-data']['exchange-documents']['exchange-document']['bibliographic-data']['parties']['inventors']['inventor'];
console.log(vm.inventors);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
vm.errorContent = [{
heading: "Error",
description: "Could not load json data "
}];
return false;
}
});
Image of successful result
Any help would be appreciated. Thank you.
if you are using x-www-form-urlencoded as header, you might need to transform your request.
var req = {
method: 'GET',
url: 'http://ops.epo.org/3.1/rest-services/published-data/publication/epodoc/US9623902/full-cycle.js',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },
};
I didn't get where the problem lies in my "GET" request. But "jsonP" method of $http did solve this issue.
#Sachila - As data is not being sent, the transformation is not required.

PUT request in node.js using $http

I'm trying to make a PUT request to a SQL database through node.js using AngularJS. I keep getting a 400 bad request error. Not sure what's wrong with the request, since this format works using a straight $.ajax call. Any help would be appreciated
vm.approveUser = function(user_id){
console.log('in approveUser');
console.log('user_id', user_id);
$http({
method: 'PUT',
url: '/admin/approve',
data: user_id
}).then(function(){
console.log('back from the /approve');
vm.getRequests();
}); //end .then function
}; //end approveUser
Try simplifying the request and add a return statement. See if it resolves.
vm.approve = function(user_id) {
var url = '/admin/approve';
return $http.put(url, user_id)
.then(function(resp) {
vm.getRequests();
})
.catch(function(error) {
})
.finally(function() {
});
};

angular post 500 (Internal Server Error) only on server

locally , with the same parameters - my post work just fine.
now when i test it on our Servers in the QA version - i get the following error
"..Services/ClearingService.svc/FunctionName 500 (Internal Server Error)"
my post look like that :
var url = baseService + "Services/ClearingService.svc/functionName";
var deferred = $q.defer();
var request = $http({
method: "post",
url: url,
data: {
payment: payment, isNotifyOnly: isNotifyOnly , isCreateDoc : isCreateDoc
}
});
request.success(function (response) {
clearingData = response.d;
deferred.resolve(response);
});
request.error(function (response) {
deferred.reject(response);
});
return deferred.promise;
as i've mentioned all the parameters are valid , and the version i have on my QA server is the same as the version on my local enviorment.
i susspect it has something to do with the WCF definitions.
any suggestions ?
It seems you're missing header information and you serializing the parameters you're posting.
Where you have
data: {
payment: payment, isNotifyOnly: isNotifyOnly , isCreateDoc : isCreateDoc
}
Change it to:
data: $httpParamSerializer({
payment: payment, isNotifyOnly: isNotifyOnly , isCreateDoc : isCreateDoc
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
I personally normally use $.param instead of $httpParamSerializer and that works for me. However $.param is a Jquery function and $httpParamSerializer is the angular equivalent, works exactly the same. Just don't forget to inject the $httpParamSerializer function.

Angular http call fails with content-type json

Here is my service:
home.factory("homeService", function ($http, $q) {
var service =
{
getAssets: function () {
var deferred = $q.defer();
var response = $http({
method: "post",
dataType: "json",
data: '',
headers: {
'Content-Type': "application/json"
},
url: "http://localhost/myWeb/services/reports_ws.asmx/getData",
});
response.success(function (data) {
deferred.resolve(data);
});
response.error(function (data) {
alert('Error');
});
// Return the promise to the controller
return deferred.promise;
},
}
return service;
I am getting 500 error from the server when I use application/json for the content. using plain/text works fine and data is returned, but in an xml format although the server sends data back in json format. I have tested it in Chrome, everything works fine. I also noticed that Chrome sends request using "application/x-www-form-urlencoded" for content-type. I tried it too, but still got data in xml. Please help.
Thanks
keep trying with the following:
header: { "Content-Type" : "application/x-www-form-urlencoded"}
Please notice that this applies only for the header of the request, not the response. The response depends on your backend (server side).
Several ways are available to return JSON data in the response depending of the type of server you are using.

Resources