AngularJS $http header for getting token - angularjs

I am very new to angularJS.
in my angular app, there is a form for login. i checked the API login endpoint on postman and i notice it generates a token after successfully logged in.
I have a form to add blog post.
I want only logged in user can add blog post. below snippet are associate with my add blog form, currently i cant post through this form, coz, it doesn't get authenticated, even if i logged in with my login form.
but it works nice on postman.
I heard of $http header but not getting how to implement this.
It falls me in trouble for last 7 days, yet i couldnt fix this issue.
can anyone help to fix this?
Thanks
$http({
method: 'POST',
url: 'http://127.0.0.1:8000/api/v1/blog',
data: $scope.formBlogModel
}).then(function (response) {
$scope.success = 'post success'
}, function(response) {
$scope.error = "an error occured";
});

Add headers property, also you can implement interceptors:
$http({
method: 'POST',
url: 'http://127.0.0.1:8000/api/v1/blog',
data: $scope.formBlogModel,
headers: {
'Authorization': 'Bearer ' + token
}
}).then(function (response) {
$scope.success = 'post success'
}, function(response) {
$scope.error = "an error occured";
});

Related

$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 ?

AngularJS - POST request does not send data after first request was successfully made

This is really weird. I am using AngularJS in my app. During login, I make an HTTP POST request ; data is sent properly and I receive the right response. Then I logout - which returns me back to the login page - and I do the same http req but the data is not sent by the post request. Upon console.log I see that the $scope data is correct - just the POST data is not being sent.
If I do a hard refresh of the login page it works again. So my problem is that consecutive requests are not being made without refreshes. Here is my login function -
$scope.login = function() {
var request = $http({
method: "POST",
url: URL + "login",
crossDomain: true,
data: this.loginData
});
request.success(function(data) {
var response = angular.fromJson(data);
if(!response["error"]) {
sessionStorage.email = response["email"];
sessionStorage.password = response["password"];
sessionStorage.userId = response["id"];
$location.path('/dashboard');
} else {
$scope.responseMessage = response["message"][0];
}
});
request.error(function(data) {
console.log(data);
});
}
And this is my logout function -
$scope.logout = function() {
sessionStorage.clear();
$location.path("/login");
}
Found the answer and posting it here in case anyone runs into a similar problem.
Setting a header for content type works:
var request = $http({
method: "POST",
url: URL + "login",
crossDomain: true,
headers: {
"content-type": "application/json"
},
data: this.loginData
});

angular laravel nginx 400 Bad Request

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({ ...... })

Token authorization - Browser throws Login form

I am working on a token implementation into Angular/.Net application. My part is the front-end. What's happening is that when UI sends a request with the expired token and the server replies with 401 I cannot intercept that before the Browser raises the Login form. As the result I cannot send a request to refresh the token. Can someone please give me an idea how that is supposed be managed? I will provide code just don't know what's to show.
Thanks
Adding code:
var response = $http({
method: "GET",
dataType: "json",
params: params,
headers: {
'Content-Type': "application/xml; charset=utf-8",
},
url: someurl
});
response = response.then(function (data) {
return data.data;
});
response.catch(function (data) {
$q.reject(data);
});
// Return the promise to the controller
return response;
The problem is that I cannot redirect on UI because Browser throws Login form before my code is hit when the server returns 401.
Make ajax request, and if you get 401 then redirect to login page.
P.s. for better understanding provide your code how you implement ajax request. Which module do you use for front-end auth? I recommend satellizer
Added:
I guess you need the following configuration on angular
var app = angular.module('App', ['satellizer'])
.config(function() {
/* your config */
}
.run(function($rootScope, $location, $auth) {
// Check auth status on each routing,
// Redirect to login page, if user is not authenticated or if token expired
$rootScope.$on('$routeChangeStart', function(event, next, current) {
if (!$auth.isAuthenticated()) {
$location.path('/auth/login');
}
});
});

cant update another user details while logged in

I'm working on nodejs loopback application. I've a user logged in already and and an operation requires this user to find a userById and update a field.
$scope.user = User.findById({
id: sender.id
});
$scope.user.supplierId = currUserId;
$scope.user.$save();
But its not working as required.
and I get following error:
PUT http://localhost:5000/api/users 401 (Unauthorized)
GET http://localhost:5000/api/AuthProviders/count 401 (Unauthorized)
401 while on router on login path
POST http://localhost:5000/api/users/login?include=user 400 (Bad Request)
Any help will be appreciated.
Thanks
For findById operation:
var url = 'http://localhost:3000/api/User/' + sender.id + '?access_token=h9vpJ94zqN199ENWx'
$http({
method: 'GET',
url: url
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(error) {
throw error;
});
Otherwise you can use Angular SDK which makes it much cleaner.

Resources