I'm trying to create $http get request to fetch some json data generated by my web service, but it returns null error. However, the $http request works fine when I use this sample url instead (it returns json string too)
This is my angular code :
angular.module('ionicApp', ['ionic'])
.controller('ListCtrl', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.get("http://localhost:8080/InventoryCtrl_Service/webresources/IVC_Service/GetUserList")
.then(function(response) {
console.log("success ");
},
function(response) {
console.log("Error : " + response.data + " Status : " + response.status);
}
});
This is my web service code :
#GET
#Path("/GetUserList")
#Produces("application/json")
public Response GetUserList() throws SQLException {
net.sf.json.JSONObject json = new net.sf.json.JSONObject();
JSONObject obj1 = new JSONObject();
JSONObject obj2 = new JSONObject();
JSONObject outerObject = new JSONObject();
JSONArray arr = new JSONArray();
obj1.put("Name", "Sara");
obj2.put("Name","David");
arr.add(obj1);
arr.add(obj2);
outerObject.put("records", arr);
return Response.status(200).entity(outerObject.toString()).build();
}
When I run the above code, it returns json string like this :
{"records":[{"Name":"Sara"},{"Name":"David"}]}
The console log returns this :
Error : null Status : 0
What is the meaning of the null error? Or is there anything wrong with how I return the json string?
Try using JSON_STRINGIFY, this will convert your incoming data into String format.
console.log(JSON_STRINGIFY(response.data));
TO verify what data your web service is returning, you can always check it by hitting your web service via postman.
I managed to solve this by adding CORS (Access-Control-Allow-Origin) to the response header, based on another SO answer. There's no problem with my angular code, it's just that I need to modify my web service code to enable the CORS. So I just modified the part where it returns data to become like this :
return Response.status(200).entity(outerObject.toString()).header("Access-Control-Allow-Origin", "*").build();
Related
I am using AWS Lambda and API Gateway and facing an issue with my API's response code,
In case of an exception I am setting responseCode as 400 in my response,
But the API status is 200.
I found that my solution is related to AWS API Gateway's Integration Response,
I created all the possible Http Status codes that my application needs,
And I set the Lambda Error Regex in Integration Response,
But I still get API status as 200 despite me sending "responseCode" : "400", in my APIs response(response type is JsonObject in Java).
I have the following code AWS Lambda code,
I am passing ErrorCode as query parameter to my Get method,
And returning the same Error code in response eg. "responseCode" : "400".
My expected output is "responseCode" : "400" but, the API's status should also become 400 instead of 200.
public class MainHandler implements RequestHandler<JSONObject, JSONObject> {
public JSONObject handleRequest(JSONObject request, Context context) {
try {
JSONObject requestJson = (JSONObject) new JSONParser().parse(request.toString());
System.out.println("RequestJson : " + requestJson);
JSONObject params = (JSONObject) requestJson.get("params");
System.out.println("Params : " + params);
JSONObject queryString = (JSONObject) params.get("querystring");
System.out.println("QueryString : " + queryString);
String error = (String) queryString.get("errorCode");
System.out.println("ErrorCode : " + error);
JSONObject resp = new JSONObject();
resp.put("responseCode", error);
return resp;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
AWS API Gateway Method Response -
AWS API Gateway Integration Response -
Postman response -
The API status shows 200 Ok, whereas I want it as 400.
I am referring the following links -
1. https://forums.aws.amazon.com/thread.jspa?threadID=192918
2. Is there a way to change the http status codes returned by Amazon API Gateway?
Your Lambda Error Regex is not a regular expression. Changing it to .*"responseCode":\s"400".* should do it.
But for that use case it would be better to activate Lambda proxy integration. This provides a more flexible way to set the response code directly from the lambda function.
I have a hashmap which I have converted into a JSONObject. This JSONObject I am retrieving via a REST api using an AJAX call. What I wish to know is that how will the ajax look like in order to get the JSONObject which I can use afterwards.
My ajax call looks like this :
Ext.Ajax.request({
url : '...',
method:'GET',
scope : this,
success : function(result, request) {
console.log("2");
var data = Ext.decode(result.responseText)[0];
for (var i = 0; i < data.size(); i++) {
console.log("4. ");
}
}
})
The error which appears is
Ext.Error: You're trying to decode an invalid JSON String:
result.responseText returns the Invalid JSON String.Use this code
var responseArray = Ext.decode(response.responseText);
var data = responseArray.data;
console.log(data);
data variable will contain the JSON Object.
I need to send the string s or json to ajax .done function. Here is the servlet code that has an object list to be sent for an ajax request.
Gson gson = new Gson();
Tester t = new Tester(10,"s");
Tester t2 = new Tester(20,"g");
LinkedList<Tester> list = new LinkedList<Tester>();
list.add(t); list.add(t2);
String s = gson.toJson(list);
I need to send the json to ajax. How could I do this? I could do :
out.println(s);
But how would I then parse the string? I need to appropriately put the json data received into the html table.
The current json output from out.println(s) is [{"x":10,"y":"s"},{"x":20,"y":"g"}]
js function that will receive json :
function getFeFeeds() {
$.ajax( {
url : '',
dataType : 'json',
type : 'GET'
}).done(function(message) {
}).fail(function(message) {
});
}}
You need to iterate over the received json and do your processing -
$.each(message, function(index, row) {
console.log(row[0].x);
console.log(row[0].y);
});
Also I would suggest set encoding so that you don't have any encoding related issues -
response.setCharacterEncoding("UTF-8");
I have servlet calling in ajax call. It send json object in response. Now I have receive this json in jsp and place data in table format. Can someone help me in this. Here is my code,
I am calling servlet as,
xmlHttpReqRM.open('POST', "RTMobitor?rtype=rmonitor", true);
my servlet, Here vehicleList is a list object
latlng.setLng(resultSet.getString("lng"));
latlng.setStatus(resultSet.getString("status"));
latlng.setRdate(resultSet.getString("rdate"));
latlng.setRtime(resultSet.getString("rtime"));
vehicleList.add(latlng);
System.out.println(vehicleList);
String json = new Gson().toJson(vehicleList);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Previously I was sending response as a text, it was easy but now I changed to json. I am not getting how to receive,
xmlHttpReqRM.onreadystatechange = function() {
if (xmlHttpReqRM.readyState == 4) {
if (xmlHttpReqRM.status == 200) {
var responceeString = xmlHttpReqRM.responseText; // How to replace this ajax code for json
document.getElementById("flexme1").innerHTML = (responceeString);
} else {
alert('ERR OR: AJAX request status = ' + xmlHttpReqRM.status);
}
How can I replace this ajax code for json. Can anyone help me in this please.
var jsonObject = JSON.parse(responceeString);
I have a JSONObject I'm sending through AJAX.
JSONObject obj = new JSONObject();
obj.put("nbLike", result);
obj.put("username", "bill");
Then in the success function I want to access the obj properties. eg : username
I'have tried with JSON.parse(obj) but I got an error : Uncaught SyntaxError: Unexpected token '
server side the log shows : {"username":"bill","nbLike":1} //log.info(obj)
client side the log show : ['username':'bill', 'nbLike':1] //console.log(result)
I'd like something like :
console.log("Username : " + obj.username)
Thank you
Convert JSONObject to String before sending it to frontend and add "application/json" to Content-type of your response. Then you can use it as simple js object, don't need to convert it.