I send a POST request to a server. As response the server send a http code and a plain text.
return Response.status(200).entity("Started").build();
AngularJS try to parse the response to json and I get a parsing error
Error: JSON.parse: unexpected character at line 1 column 1 of the JSON
data
This is my Angular code
$scope.submitForm = function() {
var url = 'http://localhost:8080/Server/server/start';
var request = $http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
return str.join('&');
},
data: {name: $scope.name}}).then(function(html) {
//success callback code
//console.log(html)
}, function(html) {
//error callback code
//console.log(html)
});
}
You need to override transform response function
$scope.submitForm = function() {
var url = 'http://localhost:8080/Server/server/start';
var request = $http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
return str.join('&');
},
transformResponse: [
function (data) {
return data;
},
],
data: {name: $scope.name}}).then(function(html) {
//success callback code
//console.log(html)
}, function(html) {
//error callback code
//console.log(html)
});
}
Related
I am very new on the forum and also with AngularJS.
I am trying to send a request to a REST server. I used this function
$scope.submitForm = function() {
var url = 'http://localhost:8080/Server/config/start';
var request = $http({
method: 'POST',
url: url,
params: {
name: 'test'
}
});
request.success(
function() {
//alert('it succeeded');
}
);
request.error(
function() {
// alert('it didnt work');
}
);
};
The code is not working properly on the server side because of some serialization stuff. I found a post on the forum that suggests using this function instead
$http({
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: function(obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
username: $scope.userName,
password: $scope.password
}
}).success(function() {});
I am not sure how to use this function with my code, I tried this code
$scope.submitForm = function() {
var url = 'http://localhost:8080/Server/config/start';
var request = $http({
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: function(obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
name: 'test'
}
}).success(function() {});
but I get an error due to the }); . Can someone help me to format and fix the code?
$scope.submitForm = function() {
var url = 'http://localhost:8080/Server/config/start';
var request = $http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {name: 'test'}}).success(function () {});
} // you need a '}' here.
also you can try the post method of $http this way.
$http.post('url', data)
.success(function(data, status, headers) { //success callback })
.error(function(data, status, headers) { //error callback });
i' using AngularJS v1.4.2. i have 2 html page , they have 2 controller.both controller have save event. how to use use http post method
first controller i'm calling post method given below
var promisePost = crudService.post(Countries);
promisePost.then(function (pl) {
alert("Sucessfully Inserted")
getCountry();
$stateParams.country = "";
}, function (err) {
alert("NOt Inserted")
});
second controller i'm calling post method given below
var promisePost = crudService.post(Levels);
promisePost.then(function (pl) {
alert("Sucessfully Inserted")
getLevel();
}, function (err) {
alert("NOt Inserted")
});
my app.js
myapp.service('crudService', function ($http, RESOURCES) {
//Create new record
this.post = function (Country) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveCountry",
data: Country
});
return request;
}
this.post = function (Level) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveLevel",
data: Level
});
return request;
}
});
but this code only take last post method.How to selecet post method properly. Anyone can helpme?
User countryPost and levelPost as follows and call those accordingly.
myapp.service('crudService', function ($http, RESOURCES) {
//Create new record
this.countryPost= function (Country) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveCountry",
data: Country
});
return request;
}
this.levelPost= function (Level) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveLevel",
data: Level
});
return request;
}
});
The best practice for using services is to return an object from it
myapp.factory('crudService', function ($http, RESOURCES) {
return {
saveCountry : function(){
return $http({
method: "post",
url: RESOURCES.baseUrl + "saveCountry",
data: Country
});
},
saveLevel : function(){
return $http({
method: "post",
url: RESOURCES.baseUrl + "saveLevel",
data: Level
});
}
}
});
then inject it into your controller dependencies and use it like :
crudService.saveLevel().then(function(){
//do some code here
})
Create a single post method instead and receive the url to call in it as parameter along with the data. As shown below:
this.post = function (data, remainingUrl) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + remainingUrl,
data: data
});
return request;
}
I'm trying to create a chat app where you can log into the incontact chat api (discard the weatherApp naming.. ).
This is the API documentation for the incontact chat api:
function startAgentSession() {
var startSessionPayload = {
'stationId': 'string',
'stationPhoneNumber': 'string',
'inactivityTimeout': 'integer - 30-300, or 0 for default',
'inactivityForceLogout': 'boolean',
'asAgentId': 'integer'
}
$.ajax({
//The baseURI variable is created by the result.base_server_base_uri
//which is returned when getting a token and should be used to create the URL base
'url': baseURI + 'services/{version}/agent-sessions',
'type': 'POST',
'headers': {
//Use access_token previously retrieved from inContact token service
'Authorization': 'bearer ' + accessToken,
'content-Type': 'application/json'
},
'data': JSON.stringify(startSessionPayload),
'success': function (result) {
//Process success actions
return result;
},
'error': function (XMLHttpRequest, textStatus, errorThrown) {
//Process error actions
return false;
}
});
``}
This is my attempt to convert in angular js, but for some reason I keep getting a 404, however, I'm at a loss for what I've done wrong..
weatherApp.controller('launchedController', ['$scope', '$http', '$document', function ($scope, $http, $document) {
$scope.clientResult = {};
$document.ready(function () {
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0; i < vars.length; i++) {
var pair = vars[i].split("=");
query_string[pair[0]] = pair[1];
}
if (typeof(query_string.access_token) != "undefined") {
var result = {};
result.state = query_string.state;
result.scope = query_string.scope;
result.access_token = query_string.access_token;
result.expires_in = query_string.expires_in;
result.resource_server_base_uri = query_string.resource_server_base_uri;
result.token_type = query_string.token_type;
}
$scope.clientResult = result;
});
console.log($scope.clientResult);
$scope.startSessionPayload = {
'stationPhoneNumber': '55555555555',
'inactivityTimeout': '0',
'inactivityForceLogout': 'false'
};
$http({
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: JSON.stringify($scope.startSessionPayload)
}).success(function(data) {
$scope.data = data;
consoloe.log('data', $scope.data)
}).error(function(status) {
$scope.status = status;
});
}]);
400 error is bad request. My guess is
replace
{
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: JSON.stringify($scope.startSessionPayload)
}
with
{
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: $scope.startSessionPayload
}
i have
$http({
url: 'http://webapi.-----UA_WebApi/GetUserAccount',
method: 'POST',
params: {Username:Username, Password:Password},
headers: { 'Content-Type': 'application/json;charset=utf-8' },
})
and in my service i wrote this method :
PostLogin: function (apiName, params) {
var fullParams = getFullParams(apiName, params);
var promise = $resource(buildUrl(apiName), {}, POST).get(fullParams).$promise;
updateAllowedFilters(promise);
return promise;
}
if anyone could help me understand what i am doing (right and wrong) pls ?
i would also like an example in how to use the angular resource for post.
the PostLogin works
PostLogin: function (apiName, params) {
var fullParams = getFullParams(apiName, params);
var promise = $resource(buildUrl(apiName), {}, POST).get(fullParams).$promise;
updateAllowedFilters(promise);
return promise;
}
.then(function (results) {
if(results.data.TotalRows==1) {}
TotalRows is undefined when debugging. but there is TotalRows in the api
thanks
var actions = {
post: {
method: 'post',
transformResponse: function(data) {
// here is your chance to change received data
return new Model(angular.fromJson(data));
}
}
};
var url = "http://postSomeData/:id/somethingElse/:name";
var parameters = { id : 1, name : "test" }
var data = { name : "test", type : "some type" };
return $resource(url, parameters, actions).post(data).$promise;
I am trying to create a factory that will return a token to the controller. This code only works as far as getting the token from the server but does not pass the token back into the controller. The token just comes back empty inside the controller. Please advise. Thank you.
securityApp.factory("getTokenFromServer", function ($http, $q) {
var token;
function getToken(userName, password) {
var deferred = $q.defer();
$http({
method: 'POST', url: 'http://localhost:62791/token', data: { username: userName, password: password, grant_type: 'password' }, transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).then(function (data) {
token = data.access_token;
deferred.resolve(token);
});
return deferred.promise;
}
return {
getToken: getToken
};
});
securityApp.controller('membersController', function ($scope, $http, getTokenFromServer) {
$scope.username = 'aharris1#test.com';
$scope.password = 'SuperPass1!';
getTokenFromServer.getToken($scope.username, $scope.password).then(function (data) {
$scope.token = data;
alert($scope.token);
$http({ method: 'GET', url: '/api/Members/?access_token=' + $scope.token, headers: { 'Authorization': 'Bearer ' + $scope.token } })
.then(function (response) {
$scope.members = response.data;
});
});
});
That is because you are not accessing the data in the right way. When using then chain of the promise the result is a combination of data, status etc.. (when opposed to success call back which breaks up pieces and give you data right up as the first argument) So i believe you should look for result.data.access_token instead of result.access_token
.then(function (result) {
token = result.data.access_token;
deferred.resolve(token);
});
And with you have you can just simplify your api method to return http promise itself rather creating a defered object:-
securityApp.factory("getTokenFromServer", function ($http, $q) {
function getToken(userName, password) {
return $http({
method: 'POST', url: 'http://localhost:62791/token', data: { username: userName, password: password, grant_type: 'password' }, transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).then(function (result) {
return result.data.access_token; //Return the data
}, function(errorResponse) {
return $q.reject(errorResponse.data);//Reject or return
});
}
return {
getToken: getToken
};
});