can't access token value from response of data - angularjs

i can't access token value from response of data from login api access please help me.
my code is accessing data from url and response is in json format from
my code is
authFactory.login = function( username, password ){
return $http.post('/api/login' , {
username : username,
password : password
})
.then( function (data) {
console.log(data);
AuthToken.setToken(data.token);
return data;
})
}
so "data" has below response in browser.
Object {data: Object, status: 200, config: Object, statusText: "OK", headers: function}
config:Object
data:Object
message:"successfully login!"
success:true
token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1OGY1ZjZlZDhlMzcyMDA4MDhkMmU4NWQiLCJpYXQiOjE0OTI1MjI1OTR9.EkTtneJvBM47LOvMUMh81XYLI_O5oByf1qjWOxliTcs"
__proto__:Object
headers:function (name)
status:200
statusText:"OK"
__proto__: Object
and if i am accessing url of login api then data is occured as
message:"successfully login!"
success:true
token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1OGY1ZjZlZDhlMzcyMDA4MDhkMmU4NWQiLCJpYXQiOjE0OTI1MjI1OTR9.EkTtneJvBM47LOvMUMh81XYLI_O5oByf1qjWOxliTcs"

Looks like when you are handling promise, you are calling response as data, try to rename it to response which is more human readable.
after renaming you can find data under response response.data.
authFactory.login = function( username, password ){
var queryParams = {
'username': username,
'password': password
}
$http.post('/api/login' , queryParams)
.then(function (response) {
// replaced data with response, which is more human readable
console.log(response.data);
AuthToken.setToken(response.data.token);
return response.data;
});
}

have you tried data.json().token ?
EDIT
One time happen to me that the I got confused with the response, because I named it data, and the response contained an object with the data.
In that case I had to use: data.data.token.
I hope this is also your case :)

Related

Angular bad data while trying to post http

I try to send some data (from a form) via $http to my backend. But I'm getting $http:baddata error when I try to send the data.
The full error is "Data must be a valid JSON object" but in my opinion, it is a valid object!
https://docs.angularjs.org/error/$http/baddata?p0=%3Cbr%20%2F%3E%0A%3Cb%3ENotice%3C%2Fb%3E:%20%20Undefined%20index:%20formData%20in%20%3Cb%3EC:%5Cxampp%5Chtdocs%5Cuno-form%5Capi%5Ccontrollers%5CFormController.php%3C%2Fb%3E%20on%20line%20%3Cb%3E26%3C%2Fb%3E%3Cbr%20%2F%3E%0A%7B%22success%22:true,%22data%22:%7B%22form%22:null%7D%7D&p1=%7B%7D
This is the code, and the console.log() result
$scope.submitForm = function(){
console.log("submitForm");
console.log($scope.formData, angular.toJson($scope.formData));
var data = {
formData: angular.toJson($scope.formData)
}
var config = {
headers : {
'Content-Type': 'application/json'
}
}
$http.post('/api/save-form', data,config)
.then(function(response){
console.log("RESPONSE", response);
},function(reason){
console.log("Err");
console.error(reason);
})
}
Console.log:
submitForm
home.controller.js:47 {firstName: "Test"} "{"firstName":"Test"}"
home.controller.js:63 Err
home.controller.js:64 Error: [$http:baddata] (...)
Model in frontend ({{formData}})
{
"firstName": "Test"
}
I have some other way's to send the data, without config, with the other $http way ($http({method: 'POST',....}) but no luck.
What I'm doing wrong here? I have created many forms and functions like this, but I never get this error...
This error can also happen when there is bad data coming from your backend, check if your response is valid.

AngularJS $http.delete not working in Azure App Service

A follow-up on a similar question I posted yesterday. I am trying to delete data from a table in Azure App service. This is my function in my Angular file.
function delName(user) {
//$scope.categories.push(user);
alert("about to delete. Action cannot be undone. Continue?")
$http.delete('https://test-evangelists-1.azurewebsites.net/tables/people', user, config)
.then(function (res) {
$scope.getNames();
});
}
Then I added an HTML button:
<button id="btn-del-evangelist" class="btn btn-default btn" ng-click="delName(user);">Delete User</button>
This is the value of my headers variable:
var config = {
headers: {
'Access-Control-Allow-Origin':'*',
'ZUMO-API-VERSION': '2.0.0'
}
};
But when I tried to run it, the console returns the following error:
which states that the header for ZUMO-API-VERSION must be specified.
Below is my code for GET and POST
GET:
function getNames() {
$http.get('https://test-evangelists-1.azurewebsites.net/tables/people', config)
.then(function (res) {
console.log(res);
$scope.people = res.data;
});
}
POST
function addName(user){
//$scope.categories.push(user);
alert("about to post!")
$http.post('https://test-evangelists-1.azurewebsites.net/tables/people', user, config)
.then(function (res) {
$scope.getNames();
});
}
Since I have already specified the header in my variable, I wonder what can be wrong here. Any help will be appreciated.
UPDATE:
I figured out that the Id must be appended to the URL before I can perform delete. However, I need to run a GET to retrieve the ID given the parameters but I am still encountering errors when getting the ID.
This is now my Delete function
function delName(user) {
alert("About to delete. Action cannot be undone. Continue?")
var retrievedId = "";
$http.get('https://test-evangelists-1.azurewebsites.net/tables/people', {
params: { name: user.name, location: user.location },
headers: { 'Access-Control-Allow-Origin': '*', 'ZUMO-API-VERSION': '2.0.0' }
})
.then(function (res) {
retrievedId = res.id;
alert(retrievedId);
});
$http.delete('https://test-evangelists-1.azurewebsites.net/tables/people/' + retrievedId, config)
.then(function (res) {
$scope.getNames();
});
}
Does anyone know what is wrong in the GET command when getting the ID?
UPDATE 2: I have written instead an Web Method (asmx) that will connect to SQL server to retrieve the ID passing the needed parameters. The ID will be returned as a string literal but in JSON format. Then I called JSON.parse to parse the string into JSON object then assigned the ID to a variable to which I appended in the URL. –
This is now my Delete function after I have written the Web Method.
function delName(user) {
var confirmres = confirm("You are about to delete this record. Action cannot be undone. Continue?");
var retrievedId = "";
if (confirmres == true) {
//get the ID via web service
$http.get('\\angular\\EvangelistsWebService.asmx/GetId', {
params: { name: user.name, location: user.location },
headers: { 'Access-Control-Allow-Origin': '*', 'ZUMO-API-VERSION': '2.0.0' },
dataType: "json",
contentType: "application/json; charset=utf-8"
})
.then(function (res) {
$scope.retData = res.data;
var obj = JSON.parse($scope.retData);
angular.forEach(obj, function (item) {
if (item.length == 0)
alert('No data found');
else {
//perform delete after getting the ID and append it to url
$http.delete('https://test-evangelists-1.azurewebsites.net/tables/people/' + item.id, config)
.then(function (res) {
$scope.getNames();
});
alert(item.id + ' deleted');
}
});
});
}
}
That is one way that I have learned on how to call HTTP DELETE on AngularJS. But I don't know if that is the optimal one. In any case, that works for me, unless there will be other suggestions.
$http.delete only has one parameter (config), not two (data, config).
Delete API
delete(url, [config]);
vs.
Post API
post(url, data, [config]);
To your updated problem:
To delete an item from your table, it appears the correct url is:
/tables/tablename/:id
Note the : before id.

Http POST request in AJAX works perfectly but not in AngularJS

I have problem with AngularJS. Im working on securing my Java Spring REST web application with Spring-Security. Im stuck on logging page - http post works perfectly using AJAX however it doesnt while using AngularJS.
jQuery(document).ready(function ($) {
$('#login-form').submit(function (event) {
event.preventDefault();
var data = 'username=' + $('#username').val() + '&password=' + $('#password').val();
console.log(data);
$.ajax({
data: data,
timeout: 1000,
type: 'POST',
url: 'http://localhost:8080/OnlineGameStore/login'
}).done(function(data, textStatus, jqXHR) {
console.log("Done!")
}).fail(function(jqXHR, textStatus, errorThrown) {
alert('Booh! Wrong credentials, try again!');
});
});
});
This AJAX code works perfectly, the credentials are properly send to the server. However:
angular.module('login').controller('LoginCtrl', function($scope, $http, $location, AuthUser ){
$scope.login = function(){
AuthUser.authenticateUser( $scope.username, $scope.password, $location ).then( function(response){
console.log(response);
});
};
});
angular.module('login').service('AuthUser', function( $http, $location ){
this.authenticateUser = function( username, password, $location ){
var absUrl = $location.absUrl();
console.log(absUrl);
var data = {
username: username,
password: password
};
var config = {
headers : {
'Content-type': 'application/json'
}
return $http.post(absUrl, data, config)
.then(
function(response){
return "Successfully logged!";
},
function(response){
window.alert("Failure!");
});
};
});
this doesnt work - data isnt even properly send to the server, instead of provided username and password all I see are nulls ( and I get 401 all the time ). URL's are the same. Can someone help me solve this?
I also tried sending bare string instead of 'data' object, it also didnt seem to work.
jQuery by default send data with Content-Type: x-www-form-urlencoded and AngularJS $http service send with Content-Type: application/json.
If you want to send data like jQuery then set the request header like this:
var data = {
username: username,
password: password
};
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
return $http.post(absUrl, data)
.then(
function(response){
return "Successfully logged!";
},
function(response){
window.alert("Failure!");
});
Remember this is global configuration for $http service.
I don't know in which technology you are running your backend, but it's often better to use default AngularJS header application/json.
What is difference?
Data in application/x-www-form-urlencoded is send by uri for example: ?parm1=1&parm2=2&parm3=3
In .NET MVC WebAPI this will be binded for:
[HttpPost]
public HttpResponseMessage Simple(int parm1, int parm2, int parm3) {
}
Data in Content-Type: application/json is send by payload in JSON format for example: { parm1: 1, parm2: 2, parm3: 3 }
In .NET MVC WebAPI this will be binded for:
[HttpPost]
public HttpResponseMessage Simple(Parameters parameters) {
}

mongoDB not inserting value using angular factory to do post method

how come its sending data to mongo if I $http.post directly in the controller?
$http.post('/api/users/', vm.newUser).success(function(response){
But using the code below doesn't seems to work, it's not passing any value but generates ID in mongoDB
vm.signupNewUser = function () {
signupService.signupNewUser(vm.newUser).success(function(response){
console.log(vm.newUser);
}).error(function(err){
console.log(err);
})
}
service:
function _signupNewUser(username, password, email, fname, lname){
var data = {
username: username,
password: password,
email: email,
fname: fname,
lname: lname
}
return $http({
method: 'POST',
url: '/api/users',
data: data
})
}
Edit: this seems to fix it, but not sure how is it different from using a direct $http.post and just passing vm.newUser. But using factory I have to pass in vm.newUser.username and etc. I don't think passing the vm like this is ideal but please correct me if I'm wrong.
vm.signupNewUser = function () {
signupService.signupNewUser(vm.newUser.username, vm.newUser.password, vm.newUser.email, vm.newUser.fname, vm.newUser.lname)
.then(function(response){
console.log(response);
console.log(vm.newUser);
});
}

$http.post in angularjs not work to me and $http.get has response errors

I am new to angularjs am tying to learn it but some problems faced me, actually they are two problems:
First Problem: $http.post never works as there is no action and there is no response. However, $http.get is able to work.
Second Problem: Because of the first problem I call my restful webservice by $http.get, but the web service response status always is -1. Though the web service is able to do its work successfully and always response data null, can any one help me.
this my angular part:
var app = angular.module('myLogin',[]);
app.controller('loginController',function($scope,$http){
$scope.login=function(){
var username = $scope.username;
var password = $scope.pass;
$http.get("http://localhost:8080/spring/webservice/login/"+username+"/"+password)
.success(function(data,status){
alert("data : "+data);
alert("Data Inserted Successfully");
window.location.href = "chatScreen.html";
})
.error(function(data,status){
alert("Status: "+status);
window.location.href = "login.html";
});
}
});
and this my web service:
/**
* web service part
*/
#RequestMapping(value="webservice/login/{name}/{pass}", method=RequestMethod.GET)
#ResponseStatus(value = HttpStatus.OK)
public ResponseEntity<String> weblogin(#PathVariable("name") String name, #PathVariable("pass") String pass)
{
System.out.print("username : "+name);
System.out.print(pass);
UserService service = new UserService();
List<UserBean> users = service.getUsers();
if(users!=null)
{
for(UserBean user : users)
if( ( user.getUsername().equals(name) ) && ( user.getPassword().equals(pass) ) )
{
System.out.print("success");
username = name;
//model.addAttribute("result", "Welcome to chat..");
MessageService messageService = new MessageService();
List<MessageBean> messages = messageService.getMessage(username);
String userMessages="";
if(messages != null)
{
for(MessageBean msg : messages)
userMessages +="\n"+msg.getSender() + ": " + msg.getMessage()+" \n";
}
else
userMessages +="You have no Messages !";
//model.addAttribute("whoSendToMe", userMessages);
return new ResponseEntity(HttpStatus.OK);
}
}
return new ResponseEntity<String>("faild", HttpStatus.NOT_FOUND);
}
refer this may be this will give you idea how to approach your problem:-
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this is asynchronous call back
// you will get your data here comming from rest
}, function errorCallback(response) {
// called asynchronously if an error occurs
});
share your code so we will try to solve it
If you use method GET and you receive a -1 returned, it means normally that you are giving a wrong URL.
As for then POST method you should use this syntax:
return $http({
method: 'POST',
url: 'index.php/email/createDeliverable',
data: $.param({
csrfTokenName: --your token--,
userName: user.name,
password: password
}),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
Remember to add the headers part.
Your server may need a CSRF token validation, in this case you need to pass it, see un my example: csrfTokenName: --your token--,

Resources