For GET request the authentication working well, but when I am trying an authentication on PUT and POST requests it asks the USERNAME and PASSWORD for infinite times.
I written an authentication code for both GET and PUT but I am unable to understand why it s happening.
Please help me.
Here my GET request code:
var session_url = '';
var username = '';
var password = '';
var basicAuth = 'Basic ' + btoa(username + ':' + password);
axios.get(session_url, {}, {
headers: {
"Authorization": + basicAuth,
"Accept": "application/json",
"Content-Type": "application/json"
}
}).then((getData) => {
console.log(getData.data);
setApiData(getData.data);
}).then(function(response) {
console.log('Authenticated');
}).catch(function(error) {
console.log('Error on Authentication');
});
Here my PUT request code:
var session_url = '';
var username = '';
var password = '';
var basicAuth = 'Basic ' + btoa(username + ':' + password);
axios.put(session_url, {}, {
headers: {
"Authorization": + basicAuth,
"Accept": "application/json",
"Content-Type": "application/json"
},
"parameters":{
"Name":name,
"Email":email
}
}).then(function(response) {
console.log('Authenticated');
alert("success");
}).catch(function(error) {
console.log('Error on Authentication');
});
"parameters" is the data in my json file.
Here my json file formate fetching from the API (This not an actual data, its just a formate of a json data)
[{"parameters":{"Name":"abc","Email":"abc#gmail.com"}}]
We have to pass body value in data parameters. Please try it.
axios.put(session_url, {}, {
headers: {
"Authorization": + basicAuth,
"Accept": "application/json",
"Content-Type": "application/json"
},
data:{
Name:name,
Email:email
},
})
for more reference check this https://stackabuse.com/how-to-make-put-http-request-with-axios/
Related
I want to send my data in headers, so I converted my data into base64 and I'm getting the output in $http.defaults.headers.common['Authorization']. But how to post the basic auth data in headers in the post request
.factory('Auth', function (Base64,$http, AuthToken) { //for login/logout
var authFactory = {};
authFactory.login = function (loginData) {
var authdata = Base64.encode(loginData.username + ':' + loginData.password);
var userData = {
username: loginData.username ,
authdata: authdata
}
$http.defaults.headers.common['Authorization'] = 'Basic ' + authdata;
return $http.post('http://cc92e1dd.ngrok.io/api/authenticate',{'Authorization':'Basic ' + authdata})//is this correct format to send?
.then(function (data) {
AuthToken.setToken(data.data.token);
return data;
});
};
Something like below, just put you params into headers:
$http.get(url,
{ headers: {
'Cache-Control' : 'public',
'Pragma': '',
'Accept-Encoding':
'gzip, deflate, br',
'Authorization': 'Basic ' + authdata
}
});
Here im trying to posting data from angular to api server in angular side it maping properly but wht it not binding at serverside
Emplyeectr.js
Emplyeeserve.js
this.saveEmp = function (savingdata) {
var sersave = $http({
url: Privateurl2+'SaveEmpData',
method: "POST",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: JSON.stringify(savingdata),
content: { 'content-type': 'application/Json' }
})
return sersave;
}
Emplyeectrl.js
$scope.SaveDb = function (user) {
if ($scope.Validate = "UpdateEmpDetails")
$scope.Submitted = true;
if ($scope.isFormValid) {
var savingdata = {
EmpName: $scope.User.EmpName,
Gen_Name: $scope.User.Gen_Name,
Email: $scope.User.Email,
Psw: $scope.User.Psw,
Cnt_Id: $scope.User.Cnt_Id,
Sts_Id: $scope.User.Sts_Id,
City_Id: $scope.User.City_Id,
}
var saving = Myservice.saveEmp(savingdata);
saving.then(function () {
})
}
}
When i trace it from Fiddler it passing data as
{"EmpName":"Aa1.com","Gen_Name":"Male","Email":"Das#gmail","Psw":"1478","Cnt_Id":2,"Sts_Id":4,"City_Id":7}
The content you are posting is not in the correct format. You are trying to post JSON but telling the server it's form data.
You should change
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
to
headers: { 'Content-Type': 'application/json' },
you should probably remove the content property as it's not in the AngularJS docs and probably a little mis-leading.
I am calling a rest API using
method is "POST"
requestData is
{
'username': user.userName,
'password': user.password,
'deviceID': deviceid,
'latlng': null,
'pincode': null
}
var req = {
method: method,
url: 'http://url/' + Api,
headers: {
'Token': 'Basic bUY5VkV0eHBOK3JUYUF1TGJjM1FHRGh4N1hYejhYSEw=',
'Content-Type': 'application/json'
},
data: {
'contentType': 'application/json',
'content': requestData
},
}
console.log(req);
$http(req).then(successCallback, errorCallback);
My rest APA is
#RequestMapping(value = "/authenticateUser", method = RequestMethod.POST, consumes = "application/json")
public AuthenticateUserBean authenticateUser(#RequestBody final AuthenticateUserBean authenticateUserBean) {
I am receiving null values for all the data such as username, password.
It is an ionic hybrid app with angular js.
I am calling it using chrome.
Cors is already disabled.
Your request format has few issues:
No need of contentType in data
You can directly send your requestData as data
Try with below code:
var req = {
method: method,
url: 'http://url/' + Api,
dataType: 'json',
headers: {
'Token': 'Basic bUY5VkV0eHBOK3JUYUF1TGJjM1FHRGh4N1hYejhYSEw=',
'Content-Type': 'application/json'
},
data: requestData,
}
console.log(req);
$http(req).then(successCallback, errorCallback);
I am trying to use Angular to authenticate against an authorization endpoint that I know works using Postman.
<script type="text/javascript">
var tokenGeneratorApp = angular.module('myApp', []);
myApp.controller('AuthenticationController', function ($scope, $http) {
var ac = this;
ac.authorizationToken = null;
ac.getAuthorizationToken = function () {
$http({
method : 'POST',
url: 'https://api.myserver.net/oauth/token',
data: {
grant_type: 'password',
username: 'theUserName',
password: 'thePassword'
},
headers: {
'Content-Type': 'application/json'
}
}).then(_authenticationSuccess, _authenticationError);
};
// Private methods to handle promise results
function _authenticationSuccess(response) {
ac.authorizationToken = response.data;
ac.resultsDisplay = ac.authorizationToken;
};
function _authenticationError(response) {
ac.resultsDisplay = 'An error occured: ' + response.data;
};
});
</script>
When I call getAuthorizationToken()I get an Http 400 back. When I look into the response.data object there is an error saying error:"unsupported_grant_type". This is confusing to me because in the Postman client I specify that the grant_type as password and all works as expected.
I must be doing something wrong in the Angular code.
Had a very similar problem recently. Try removing the 'headers' and insert 'dataType' instead, as follows:
$http({
method : 'POST',
url: 'https://api.myserver.net/oauth/token',
dataType: "json",
data: {
grant_type: 'password',
username: 'theUserName',
password: 'thePassword'
}
EDIT
$http({
method : 'POST',
url: 'https://api.myserver.net/oauth/token',
data: {
"username=" + theUserName + "&password=" +
thePassword + "&grant_type=thePassword"
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
//resolving => error:"unsupported_grant_type"
vm.BtnLogin = function () {
$scope.txtUsernamee;
$scope.txtPasswordd;
var client_credentials = $scope.txtUsernamee + $scope.txtPasswordd;
var auth = 'username=' + $scope.txtUsernamee + '&' + 'password=' + $scope.txtPasswordd + '&grant_type=password';
$http({
method: "POST",
url: '/token',
contentType: 'application/json',
data: auth
}).then(function success(response) {
//$('#successModal').modal('show');
console.log("ok")
},
function error(e) {
console.log(e)
}
);
};
i am new in programming and angular.
i have the data like this in my controller
temanService.create({
Userid: $scope.datateman.userid,
Address: $scope.datateman.address,
Employeeid: $scope.datateman.employeeid,
Email: $scope.datateman.email,
Phoneno: $scope.datateman.phoneno,
Password: $scope.datateman.password,
Division: $scope.datateman.division,
Leavebalance: $scope.datateman.leavebalance
}).success(function(data) {
$scope.showAlert({
title: "Information",
message: "Data Telah Tersimpan"
});
});
and this is my service for http.request
angular.module('starter.services', [])
.factory('temanService', function($http) {
var baseUrl = 'http://localhost:60820/MobileBootcamp.svc/';
return {
create: function(datateman) {
return $http.post(baseUrl + 'insert?method=insertuser',
datateman, // <--- what to insert here
{
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
});
},
update: function(datateman) {
return $http.post(baseUrl + 'update.php', datateman, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;'
}
});
},
delete: function(id) {
return $http.get(baseUrl + 'delete.php?id=' + id);
}
};
});
and this is example of the correct parameter for insert
{
"Value": "userid|address|employeeid|email|phoneno|password|division|leavebalanc"
}
My question is,
How to put data to the http request post method?
i wanted to make like this
method: 'POST',
url: 'http://110.35.82.163:9090/MobileBootcamp.svc/insert? method=insertnews',
crossDomain: true,
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
data: { "Value": userID + "|" + $scope.title + "|" + $scope.posttag + "|" + $scope.content }
Try this
var data = {
Userid: $scope.datateman.userid,
Address: $scope.datateman.address,
Employeeid: $scope.datateman.employeeid,
Email: $scope.datateman.email,
Phoneno: $scope.datateman.phoneno,
Password: $scope.datateman.password,
Division: $scope.datateman.division,
Leavebalance: $scope.datateman.leavebalance
};
var dataCollection = [];
for(var item in data){
if(data.hasOwnProperty(item)){
dataCollection.push(data[item]);
}
}
var DTO = {
Value: dataCollection.join('|');
};
//do not use success. its obsolete
temanService.create(DTO).then(function(response){
},function(response){
//error
});
Writing service like this will be more readable.
create: function(datateman) {
var config = {
method: "POST",
url: baseUrl + 'insert?method=insertuser',
data: datateman,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
};
return $http(config);
}
Just add data attribute to your service.
For your code add like the following
create: function (datateman){
return $http.post(baseUrl+'insert?method=insertuser',datateman,{
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
});
This is the documentation
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
In your code you can do
var data = { "Value": datateman.userID + "|" + $scope.title + "|" + $scope.posttag + "|" + $scope.content } + 'your next values'.
$http.post(baseUrl+'insert?method=insertuser', JSON.stringify(data) ,{
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
});