$http - post - Bad request error not handled (undefined) - angularjs

I am trying to do a POST to create an account and I am expecting a 400 Bad Request (Username already used or Email already used).
I have confirmed with other tools (RESTED for firefox) that I am receiving the correct 400 Error with my message, but with AngularJS response.status, response.data and response.statusText all give an 'undefined' value.
Below is the definition of my request in AngularJS:
var req = {
method: 'POST',
url: myURL,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
data: $scope.user
};
$http(req).then(
function(response){
console.log("account created perfectly!");
},
function(response){
console.log("ERROR " + response.status + ": account cannot be created!");
// the data is Username/Password
alert(response.data + " invalid!");
}
)
What am I doing wrong?

Can you post your inspector screenshot here?
Looks like there is some issue with the passing of request body.
The 4xx error comes when the client sends a bad request.
Also, for your use case, return status code 2xx as this is the valid business case and it should not be 4xX.

Related

POST request with axios ReactJS

I'm new to HTTP requests and trying to do POST request of my form submitting with axios and getting an error 400. I want to send my data to url and it should be seen there in JSON format.
codesandbox https://codesandbox.io/s/fast-brook-g3488?file=/src/App.js
Error is very clear you are not passing data to axios post method.I am not sure what kind of validation you have in server but it will be look like this
axios({
method: "post",
url: "https://frosty-wood-6558.getsandbox.com:443/dishes",
headers: { "Content-Type": "application/json" },
data:{
name:event.name,
preparation_time:event.preparation_time,
type:event.type,
spiciness_scale:event.spiciness_scale,
}
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
Since its now throwing error preparation time validation. Not sure what's the validation you have in server side
preparation_time: "Wrong format"

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.

restdb.io wont let me access with GET verb although I got CORS enabled

I have CORS enabled in restdb.io. I have set up so all origins are allowed to make GET requests. I have generated a Api key .This is the error message and api call. The wierd thing is that if I click the request in the network tab in chrome dev mode I can see it got 200 ok from the server. Am I missing something?
No 'Access-Control-Allow-Origin' header is present on the requested resource.
I am using Angular JS.
function getImages() {
var def = $q.defer();
$http({
async: true,
crossDomain: true,
url: getImagesURL,
method: "GET",
headers: {
"content-type": "application/json",
"x-apikey": APIKEY,
"cache-control": "no-cache"
}
}).then(function successCallback(response) {
def.resolve(response.data);
}, function errorCallback(response) {
console.log("Error " + response.data)
});
return def.promise;
}
Solved it. I was using the wrong api key.

Fetch Angular $http response header param

I am working on an Progressive Web app module with AngularJS.
I have made a network call with POST request using '$http', I am able to get a response of it but am not getting 'Response Header' params.
Here is my Response header:
Connection:keep-alive
Content-Type:application/json
Date:Fri, 19 May 2017 10:41:49 GMT
Server:JBoss-EAP/7
Session-ID:XXXXX-YYYY-ZZZ
Transfer-Encoding:chunked
X-Powered-By:Undertow/1
And below is a request and API call.
$scope.data = {userid: $scope.username,
os: 'android',
device_id: 'b0316b93ae786ec0',
source: 'iv2',
password: $scope.password,
build_version_code: '2.3',
version: '5.1.1'};
$http({
method : "POST",
url: 'https://domain.name/v1/users/login',
data : $scope.data,
headers: {
'content-type': "application/json",
'sessionID': ''
}
})
.then(function successcallback(response){
console.log("Session-ID" , response.headers());
console.log("response" , response);
}, function errorcallback(response){
console.log('error' , response);
});
I have tried below possible solution based on response callback method.
function successcallback(response){
response.header('Session-ID');
}
and
success(function(response , status , headers , config){
console.log("response" ," headers - " + headers('Session-ID'));
}
The both approaches returns a null value instead of expected value.
Please let me know if I am missing something. I am happy to get all possible help.

AngularJS HTTP GET request returning cached data

In my AngularJS app I am sending HTTP GET request as below.
MyService.HttpReq("testUrl", "GET", null);
HttpReq Method is defined in a service and implemented as below:
this.HttpReq = function(URL, method, payload)
{
$http({
url: URL,
method: method,
cache: false,
data: postData,
headers: {
'Content-Type': 'application/json',
}
}).success(function(response)
{
console.log("Success: "+JSON.stringify(response));
}).error(function(data, status)
{
console.error("Error");
});
}
First of all is this the right way of sending HTTP request in AngularJS?
The problem that I am facing is, some times I get cached data as response and HTTP request is not hitting the server. what can be the issue?
UPDATE
As per the comment and answer I have updated my HTTP request code as below, but still getting same issue.
this.HttpReq = function(URL, method, payload)
{
$http({
url: URL,
method: method,
cache: false,
data: payload,
headers: {
'Content-Type': 'application/json',
'Cache-Control' : 'no-cache'
}
}).
then(
function(response)
{
var data = response.data;
console.log("Success: "+JSON.stringify(data));
},
function(response)
{
var data = response.data || "Request failed";
var status = response.status;
console.error("Error: "+JSON.stringify(data));
}
);
}
IE Browsers will catch ajax get requests even if we add cache control headers to the response. Only way i found to solve the issue is to add some random parameter to the request. Please make sure the api have no problem even if you send extra parameters
MyService.HttpReq("testUrl?ts=" + Date.now(), "GET", null);
Just add cache: false attribute to config object.
https://docs.angularjs.org/api/ng/service/$http#caching
Also you can add header: 'Cache-Control' : 'no-cache'

Resources