How do I get a JSON object from an Http Response? - json

I have the following api call in my service:
getData() {
return this.http.post<Object>(this.base_URL + "web_app/login/", JSON.stringify(this.login))
.subscribe(response=>{
console.log(response);
})
The response is an object with two attributes, access_token and Success. I get the following in my console:
{access_token: "...", Success: "Success"}
Success: "Success"
access_token:"..."
When I try to access the access_token attribute, using response.access_token, I get an error. Why is this and how do I fix it? Is the response I'm getting an object? Thank you!
Edit: this is what console gives
enter image description here

As your image shows you are getting the response on console, try accessing it as follows,
.subscribe(response=>{
console.log(response['access_token']);
})

Related

Http failure during parsing for url

login.ts
onLogin() {
let input = new FormData();
input.append('email','ajith#gmail.com')
input.append('password','12356789')
this.http.post('http://worthyconsultants.in/training/api/v1/user/login',
input,{responseType: 'json'}).subscribe(res=>{
console.log(res)
},
err=>{
console.log(err)
})
}
This is my Login function but the response is an error.says parsing error
First you conform your post request send using POSTMAN tool if yes follow this link it help you or it may be backend side issue
[enter link description here][1]
https://www.youtube.com/watch?v=HgKx36cpu60
There was a print statement at the backend code,That's why it seems fine in the postman pretty view.

How to generate specific json with jqwidgets and angular?

I'm trying to export the data of my datatable into a json file.
The table is create with JQwidget on Angular6 and the data come from an API.
But, with the jqwidgets method exportData('json');, only can make a format of a json of the table.
[{"id":"1","name":"test"},
{"id":"2","name":"toto"}]
jsonExport(): void {
this.myDataTable.exportData('json');
};
I don't know how to change the format of the json to have something like that:
["number":"2",
"1":{"id":"1","name":"test"},
"2":{"id":"2","name":"toto"}]
Thanks
I manage to do what I wanted, it goes like that:
First, You can't do it with JqWidgets https://www.jqwidgets.com/community/topic/how-to-generate-specific-json-with-exportdatajson-jqwidgets-and-angular/
Then, my solution is:
I created the String inside my Nodejs API as a GET.
app.get('jsonfile', function (req, res) {
res.header("Content-Disposition", "attachment;filename=\filename.txt\"");
connection.query('select * from heroes', function(error, results, fields) {
if (error) throw error;
var JSONstring = "[";
...
...
...
JSONstring = "]";
res.end(JSONstring);
console.log(JSONstring);
});
});
res.header('Content-Disposition', 'attachment;filename=\filename.txt\""); is mandatory for my solutio if you want to make this JSON string downloalable as a file.
I tried to use this end-point just like the others but I had this problem :
ERROR
Object { headers: {…}, status: 200, statusText: "OK", url: "http://localhost:3000/jsonfile", ok: false, name: "HttpErrorResponse", message: "Http failure during parsing for http://localhost:3000/jsonfile", error: {…} }
Because it was not working with a button click and ts function.
Instead I just made this:
<a href="http://localhost:3000/jsonfile" ><button>Creation JSON File</button></a>
It works for me, but if there are better solutions, I will be glad to know.
Thanks all for your help!

JSON value truncated in server

var authOptions = {
method: 'POST',
url: url,
data: options.data,
headers: options.headers,
json: true };
return axios(authOptions)
.then(function(response){
console.log(response.data);
})
.catch(function(error){
console.log(error);
});
This is my code snippet. I am trying to make a request to an URL which works fine in my local system. But, when I am running this code inside a windows-server, the JSON returned is incomplete and truncated. It throws an error, unexpected end of JSON. I have tried using the node-rest-client and request as well, but the error persists. any insights into this issue ?
TIA
Turns out this is not a problem with the nodejs code. Windows network settings have put some restrictions on size while receiving the data. Once those restrctions are removed, it works like charm.

Request Media Type[application/json] Error! Request Body is not JSON format issue for Extjs Ajax request

I am using Extjs 5.1.3. I have post request with params as-
{"root":{"countryId":"458","ruleId":"3386","ruleName":"Test1 \\","ruleType":"CELL_STORE","opType":"DETAILS"}}
I am creating ajax request as-
Ext.Ajax.request({
method: 'POST',
url: appurl.fetchRuleDetails,
params: win.jsonData,
callback: function(option, success, response){
})
})
From server side, response is coming as-
{
"rules":[
{
"countryId":"458",
"ruleId":"3386",
"ruleName":"Test1 \\",
"ruleType":"CELL_STORE",
"ruleParts":[
{
"seq":"1",
"attrId":"6",
"attrName":"Store Type",
"op":"=",
"val":"dsafdaf",
"charType":"GLOBAL_CHAR"
}
]
}
],
"Status":{
"StatusFlag":true,
"StatusCode":"SUCCESS",
"StatusMessage":"SUCCESS"
}
}
But in Ajax request's callback function, we are receiving response.responseText as-
Request Media Type[application/json] Error! Request Body is not JSON format.
My guess is like issue is because of rulename value as "Test1 \".
So can someone please help me whats missing.
The error message is not an ExtJS error message. If you receive an ExtJS error related to invalid JSON, it will look like this:
Uncaught Error: You're trying to decode an invalid JSON String: TestTest
My best guess is that the error message comes from the server, because it expects you to send your request as JSON. Right now you are sending it as FormData. To send the request as JSON, you have to put your object in the jsonData config and leave the params config undefined:
Ext.Ajax.request({
method: 'POST',
url: appurl.fetchRuleDetails,
jsonData: win.jsonData,
callback: function(option, success, response){
})
})
For future questions regarding server-client communication, please keep in mind that you should first check in your browser network tab what you send to the server and what the response from the server really is.

jQuery not handling JSON response from AJAX POST

Updated: I'm posting HTML FORM data but expecting to receive JSON data. I am not trying to POST JSON data.
I am trying to get a JSON response back from doing a HTML FORM POST request. I have successfully received a JSON back when using a simple HTML FORM POST request (i.e. not AJAX). My JSON response from the HTML FORM POST is this:
{"success":true,"data":1234567}
The problem occurs when I try to handle the request and response with jQuery's .ajax().
$.ajax({
type: "POST",
url: URL,
data: data1,
dataType: "json",
success: function(data, textStatus, jqXHR) {
alert ("success");
},
error: function(xhr, status, error) {
alert ("Error: " + error);
}
});
After running the above code and debugging in Firebug, it appears that the POST request is going through, but something is going wrong on the handling of the response. Firebug tells me the following regarding the HTTP response from the POST request:
Response Headers
Cache-Control private
Content-Length 31
Content-Type application/json; charset=utf-8
...
So it appears that the 31 bytes of data is being sent. However, when debugging the actual Javascript, the error function gets called and the xhr object is this:
Object { readyState=0, status=0, statusText="error"}
I know the jQuery.ajax() document states that "In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown." However, I believe my JSON is valid as I have checked it at jsonlint.com.
What else could be going wrong?
It looks to me like you are getting a server error. I would check the status code of the response and fix whatever is causing the request to fail on the server.
your getting an error because data1 is not formatted in json, so when it receives the data it gets a parse error. data1 needs to be formatted:
data1={"apikey":apikey,
"firstname":fName
}
I was having the same problem. It seems that this is an issue with Cross Domain.
Finding this SO answer: https://stackoverflow.com/a/7605563/154513
helped me.
Some times Jquery return Internal Error 500 for currectly data.
There is example for read the same json data withour error
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://reqres.in/api/products/3", true);
xhr.onload = function(){
console.log(xhr.responseText);
};
xhr.send();