Strange behaviour of response when it isn't json in angularjs get - angularjs

I have problem with error in angularjs:
Error: [$http:baddata] Data must be a valid JSON object. Received: 'test string test string' Parse error: "{}"
So if I understand it correctly, the response from the server hasn't good JSON format. Let's say that I can't change it on the server side and I try to repair it on the frontend.
So I try to use transformResponse:
function testFunc() {
return $http.get('url', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
transformResponse: function(data)
return {'status': data}
}
})
}
And then, ok, I haven't errors and everything looks fine but I expected in response something like that: {"status": "test string test string"}
But instead, I have html code from whole my site ({"status": '<HTML>....'}) Why data isn't this string which was when it was the error? How can I deal with it?

Related

Multiple response types in a single $http call [duplicate]

I have an Angular 1.x application that is expecting to receive a binary file download (pdf) using a $http.post() call. The problem is, I'd like to alternatively get a processing error message that's sent as json. I can do this with the config
headers: {
'Accept': 'application/pdf, application/json'
}
The problem is I have have to set responseType: 'arraybuffer', otherwise the pdf binary is escaped (or altered such that it doesn't load). However, that prevents the json from being read or interpreted correctly.
How can I have both?
Edit: I'm going to try to clarify; perhaps my understanding is incorrect.
$http({
method: 'POST',
url: "/myresource",
headers: {
'Accept': 'application/pdf, application/json'
},
responseType: 'arraybuffer'
})
.then(
function(response) {
// handle pdf download via `new Blob([data])`
}, function(response) {
// pop up a message based on response.data
}
)
In a scenario where I return a pdf data block and a http status of 200, the first function handles the response and prompts the user to save the file. However if the status is an error (422), the response.data is undefined. I assume this is because the responseType is preventing the json from being handled correctly.
If I remove the responseType line, the error data is correctly read, but when the pdf is saved, some of the file bytes aren't correct and it's effectively corrupted. I assume this is because the file is being encoded because javascript was expecting a string.
An XHR responseType property can not be changed after a response has been loaded. But an arraybuffer can be decoded and parsed depending on Content-Type:
var config = {
responseType: "arraybuffer",
transformResponse: jsonBufferToObject,
};
function jsonBufferToObject (data, headersGetter, status) {
var type = headersGetter("Content-Type");
if (!type.startsWith("application/json")) {
return data;
};
var decoder = new TextDecoder("utf-8");
var domString = decoder.decode(data);
var json = JSON.parse(domString);
return json;
};
$http.get(url, config);
The above example sets the XHR to return an arraybuffer and uses a transformResponse function to detect Content-Type: application/json and convert it if necessary.
The DEMO on PLNKR

Angular $http post call passing data issue to GO backend

I am trying to get access to backend written in GO which in 99% is good (problem does not lay there).
For now I just created simplest call which stay in controller (it will be in service in future) to register new user. Although I hardcoded data which I am passing the response says 403 forbidden. In powerShell shows reason of 403:
RegistrationForm parse - email: , nick:
Validation failed for email - blank
It looks like I am not passing my data correctly because email is blank. Please take a look at my code:
$ctrl.fake_registerSubmit = function() {
$http({
url: 'http://localhost:3000/v1/sign_up',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'POST',
data: {
email: 'check#onet.pl',
nick: 'borysxoxo',
password: 'admin12312',
password_confirmation: 'admin12312'
}
})
.then(function successCall(response, post) {
console.log('user added');
}, function errorCall(respone) {
console.log('error callback');
console.log(respone);
})
};
This screenshot presents API documentation which I am trying to access:
link
What am I doing wrong? Is there other way to pass data?
You are sending some json data with the wrong Content-Type.
I see 2 options, either change Content-Type in your header to:
'Content-type' : 'application/json'
or transform your payload to:
data: "email=check#onet.pl&nick=borysxoxo&password=admin12312&password_confirmation=admin12312"

angular POST not working with servlet

I am trying to use angularjs POST (or even GET) to a servlet with the following:
var json = { hello: "world" }
var deffered = $q.defer();
$http({
method: "POST",
url: url,
headers: { "Content-Type" : "application/json" },
request: JSON.stringify(json)
}).then(data) {
if(data.data) {
deferred.resolve({
response : data
});
)
})
return deffered.promise;
within the servlet, simple:
String val = request.getParameter("request")
it never seems to see it
I have tried:
data: JSON.stringify({ request: json })
data: { request: json }
"request" : JSON.stringify(json)
etc
if I comment out the getParameter and just return a generic value using Gson
JsonObject json = new JsonObject();
json.addProperty("This", "works");
response.getWriter().print(new Gson().toJson(json));
that comes back fine so is there something within the angular POST I am doing wrong here? I have also tried using "GET" instead but same result.
EDIT: I would like to understand POST method and the "proper" way to get the data from the json object if getParameter is wrong please~
getParameter() returns http request parameters, you should add this params by using :
params: JSON.stringify(json)
Not with
request: JSON.stringify(json)
Take a look in params in get and params in post.

Is it not possible to send an array with GET method?

On the server side I have a method that accepts an array of integers and returns a Json object:
public JsonResult GetCorrespondingOfficers(int[] categories){
//use `categories`
return Json(model,JsonRequestBehavior.AllowGet);
}
And I have the following script on the client:
var categories=[1,2,3];
$.ajax({
url: url,
type: 'GET',
data: { categories: categories },
contentType: 'application/json; charset=UTF-8',
dataType: 'json',
success: function (data) { alert('Success');},
async: false
});
When I run the above code I get null for the parameter categories on the server side. If I change the method from GET to POST, then it works. Does it mean that I can't send an array or any Json data with GET request? If not, then what's the problem with my code?
You can send array as a string:
...
data: { categories: JSON.stringify(categories) },
...
GET request does not have message body, so you can't use GET with contentType: 'application/json; charset=UTF-8'. When you use json in GET request, browser breaks your json and append each josn key value to the url(even if you use JSON.stringify method). Therefore for using json and REST you need to use POST method.

How to Format Rexster POST to Add an Edge to a Titan Graph

I'm attempting add an edge to my Titan Server 0.4.4 graph using an AngularJS resource. The resource looks like this:
'use strict';
angular.module('storymapApp').factory('edgeResource', function ($resource) {
var EdgeResource = $resource('http://localhost:8182/graphs/graph/edges?_outV=:outId&label=:label&_inV=:inId', {outId: "#outId", inId: "#inId", label: "#label"}, {
update: {method: 'PUT', isArray: false},
outedge: {method: 'POST',
transformResponse: function(data, headers){
// deserialize the JSON response string
data = angular.fromJson(data);
data = data.results;
return data;
},
isArray: true}
});
return EdgeResource;
});
This code generates a POST like this:
http://localhost:8182/graphs/graph/edges?_outV=120028&label=contains&_inV=160076
which returns the following 500 error message:
{"message":"An error occurred while generating the response object","error":"Edge cannot be found or created. Please check the format of the request."}
Where is the formatting issue in the request?
Can you change your angularjs code to POST the request as JSON (instead of formatting the parameters to query string)? Set your Content-Type to application/json as well (though angular may be doing that for you already. Those things should fix your problem.

Resources