Sending Data Error with angular's $http.put - angularjs

Whenever i fire this put method :
return $http.put('/posts/' + post._id + '/upvote', {
headers: {Authorization: 'Bearer '+auth.getToken()}
}).success(function(data){
post.upvotes += 1;
});
I get the following error :
PUT http://localhost:3000/posts/56d89bfbb906ee1305fea2cf/upvote 401 (Unauthorized)
From what I understand, this is an angular issue with the way that its put method supports sending data to the server.
Can anyone who has dealt with this issue before help me out by.
-Thank you very much in advance

Try setting the HTTP header before hand:
$http.defaults.headers.common.Authorization = 'Bearer '+ auth.getToken();
Then call your PUT request

Related

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

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.

$http GET request not reaching server from AngularJS app

I have a REST API deployed on localhost with the following GET endpoint: localhost:9000/get-events/1
This endpoint is returning the correct response when I send the request through Postman or through a web browser. It also contains CORS headers etc, and I have also handled the options requests with appropriate headers. (The server is implemented in Play Framework).
The response from Postman for the above GET request is:
headers:
Access-Control-Allow-Origin →*
Content-Length →34
Content-Security-Policy →default-src 'self'
Content-Type →application/json
Date →Tue, 10 Apr 2018 04:50:16 GMT
Referrer-Policy →origin-when-cross-origin, strict-origin-when-cross-origin
X-Content-Type-Options →nosniff
X-Frame-Options →DENY
X-Permitted-Cross-Domain-Policies →master-only
X-XSS-Protection →1; mode=block
body:
{
"status": "success",
"events": "[<some list....>]"
}
I basically want the list that is being returned by the server to be loaded in a ng-repeat list in my Event List page when the user is navigating to it. I have implemented this in my code like this:
inside the controller in app.js:
$scope.getlist = function() {
$http({
url: 'localhost:9000/get-events/1',
method: 'GET'
}).then(function (response) {
console.log('SUCCESS: ' + JSON.stringify(response));
$scope.events = JSON.parse(response.data.events);
}, function (response) {
console.log('ERROR: ' + JSON.stringify(response));
});
}
and in the front end, index.html:
Fetch List
and, eventList.html:
<ul>
<li data-ng-repeat="event in events">{{event.name}}</li>
</ul>
When I click on the link, it gives the following error in the browser's console:
ERROR: {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"localhost:9000/get-events/1","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":""}
from the server logs, it seems that the request is not reaching the server at all.
The strange thing is that I am also sending a POST request to the same server, while doing the user login and that request is successfully reaching the server and correctly giving the response from the angularJS app.
This is how I call the POST from my angularjs controller:
$scope.login = function () {
console.log('login called');
var loginURL = 'localhost:9000/login';
var loginInfo = {
'email': $scope.email,
'password': $scope.password
};
$http({
url: loginURL,
method: 'POST',
data: loginInfo,
headers: { 'Content-Type': 'application/json' }
}).then(function successLogin(response) {
console.log('SUCCESS: ' + JSON.stringify(response));
}, function failLogin(response) {
console.log('ERROR: ' + JSON.stringify(response));
});
}
What am I missing while doing the GET request?
In the server have you added CORS header Access-Control-Allow-Origin in server end ?
Its Working for me
try this.
html:
<a ng-click="getlist()">Fetch List</a>
js:
$scope.getlist = function () {
$http({
url: 'ControllerName/getevents/1',
method: 'GET'
}).then(function (response) {
console.log('SUCCESS: ' + JSON.stringify(response));
}, function (response) {
console.log('ERROR: ' + JSON.stringify(response));
});
}
output in console:
SUCCESS: {"data":"","status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"Employee/getevents/1","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"OK","xhrStatus":"complete"}
So, I was running my Angular App using Firefox earlier and I just thought of using Google Chrome. It helped me by providing this extra information in the console:
Failed to load localhost:9000/volunteer-events/1: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
So, it seems that in the HTTP get URL I was just using localhost:9000... instead of the complete http://localhost:9000...
changing my URL to http://localhost:9000... fixed the problem.
Answering this here so that anyone else who was stuck on this for long time like me would benefit from it!
Although I am still not sure how it worked for the POST ?

Symfony + AngularJS 401 unauthorized error after Get method

I have some concerns(marigolds) with my method GET when I send my request. I have received an error 401 and I am disconnected from the application, knowing that the token which I obtain in the console is very valid when I test on postman. I does not really understand(include) why that does not work I have to add some things or I have pain make something.
var list = function(){
var mytoken = window.localStorage.getItem('token');
return $http({
method : 'GET',
url : apiEndpoint.url + '/list',
withCredentials : true,
headers : {Authorization : 'Bearer ' + mytoken}
}).then(function(res) {
console.log(res.data);
});
};
If somebody could me helped please, thank you :)
I think that she uses of the angularJS in her project, while RequestOptions is a class which we find that in Angular 2. That's why the import does not work
It must be added in the conf of apache:
SetEnvIf Authorization. + HTTP_AUTHORIZATION = $ 0
It should work for your case :)
Please check it like below:
let headers = new Headers();
headers.append('Authorization', 'Bearer ' + YourToken);
let options = new RequestOptions({ headers: headers });
this.http.get('YourUrl', options)
This should work

Angularjs: Why does adding an authorization header cause a -1 status response?

I have a pre-existing angular code that gets data from an API. I'm trying to add an authentication token to the request.
To begin with I tried a simple example
.factory('getDep', [
'$resource', function($resource) {
return $resource('/ContactsDatabaseAPI/deps/:id', { id: '#id' }, {
query: {
method: 'GET',
isArray: false,
headers: {
'Authorization': 'Bearer ' + token
}
},
create: {
method: 'POST'
},
update: {
method: 'PUT'
},
remove: {
method: 'DELETE'
}
});
}
When the GET call is fired, and F12-ing in Chrome, I get an error message of:
angular.js:11821 OPTIONS http://localhost:56057/ContactsDatabaseAPI/deps net::ERR_CONNECTION_RESET
The return status of -1 and no sign of the call making it to the server side.
Without the headers line, it works fine.
If I try the GET call in Postman with the same Authorization value in the header, this also works fine.
I've also tried to add the header in the httpInterceptor and get the same result:
config.headers = config.headers || {};
config.headers.Authorization = 'Bearer ' + authData.token;
Other things I've tried:
A random header name causes the same issue.
I've added 'Content-Type' = 'text/plain; charset=utf-8' as a header. This has no change to the result
I'm using angular 1.5.6
try this (in the controller) :
$http.defaults.headers.common.Authorization = 'Bearer ' + token;
I've solved my issue and thanks to #Mourad-Idrissi for pointing me in the right direction.
The reason it worked before is that there was no Pre-Flight checks before the API was run. When I added the header, this changed the way the client communicated to the API. Now there was a OPTIONS call to the API which was causing the error. As the domain was different, this introduced me to the world of CORS.
By adding the following to my Application_BeginRequest() method in my backend Web API, Pre-flight now passes and my application continues.
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}

AngularJs http request header is not changing

I'm getting a problem when I try to call my WebApi, I need to send in a request header the authorization credentials, but, I'm not getting it up.
My resquest header need to be like this image of the request header generated by my REST tester
Authorization:Basic dXNlcm5hbWU6cGFzc3dvcmQ=
But, when I try to set it on Angular using this code block
$http.defaults.headers.Authorization = 'Basic ' + credentials;
return $http.post('http://localhost:2703/api/Authenticate');
Or this
return $http.post('http://localhost:2703/api/Authenticate', {
headers: { 'Authorization': 'Basic ' + credentials }
});
My request header became like this one
Access-Control-Request-Headers: accept, authorization
Can someone tell me what am I doing wrong? Any help will be appreciated. :)
You can do something like this:
var header = {headers: {'Authorization': 'Basic ' + credentials}}
$http.post(url, payload, header)
.success(function (data) {
//stuff
}
I couldn't resolve my problem using a cross domain request, so, I've configure my Web Api and Web App in the same domain. Doing this, I can change the headers normally and send a post request as I need.

Resources