I need to access properties from this object, but I am getting undefined.
I tried use JSON stringify and parse but without success.
console.log('ress', response.data);
console.log('ress data', response.data.url);
console.log('ress key', response.data.key);
output:
ress {"url":"my url","key":"my key"}
ress data undefined
ress key undefined
Probably your response.data object is a string, in this case you have to parse it into a JSON object to be enable to access the properties.
object = JSON.parse(response.data);
console.log('data url', object.url);
Related
I need some clarification on JSON objects. Inside my node backend, I receive a JSON object and after I'm done going through which key/value pairs I need, I send it off to the frontend. This is where I'm getting confused- I still need to turn that response object into json via response.json(). Why? If the backend is passing JSON, then why would I need to turn the response obj into JSON?
// test.js (node)
const testObj = {
"test1": {
"1": "Hello there"
}
}
app.get('some-route', async(req,res) =>{
res.send(testObj)
}
// front.js (React)
async someFunc(){
const response = await fetch('/some-route');
const data = await response.json(); //why?
}
Because on your front-end, the fetch API receives a buffer -- an array of bytes, which could contain any payload. It could be an image, plain text, a file, or a JSON payload.
Knowing what your back-end is going to send down, you need to receive the buffer of the data and then perform the .json() API on it, essentially asking that the buffer be interpreted as a serialized string representing a JSON object, and then having the Javascript engine evaluate (deserialize) that string into an object.
Fetch is a multi-purpose API that doesn't have any prior knowledge about the payload that the server is going to send. You are instructing it to treat the payload as JSON by using the .json() function.
Besides .json(), there are other helper methods to read and parse a variety of other possible response types; for example, .text() for plain text, .formData() for form encoded data (similar to querystring values), .blob(), and .arrayBuffer() for byte-level access to the returned data. You will use the appropriate method based on the response type that you're expecting from the API.
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
The response object isn't whatever you sent from the backend, it will be a Response object. That's how the Fetch API works. That Response object will have lots of metadata on it, and some methods, including .json which Takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.
If you don't want to have to go through these two steps, just write this function.
const fetchJson = async url => {
const response = await fetch(url)
return response.json()
}
and use it like this:
async someFunc(){
const data = await fetchJson('/some-route')
}
A response object is more than just its JSON part. It contains all HTTP protocol elements, like headers, the state of the response and so on.
When you use res.json() you are telling your code to separate only the JSON part from all these other things.
To understand a bit more about an HTTP response, I suggest you to read this.
Good question!
When you send data to the front-end from the back-end, you're not just sending the data payload you created in your testObj. What's actually being returned is a response object, which will look something like:
{
type: "cors",
url: "http://some-url.com/some-api",
redirected: false,
status: 200,
ok: true,
body: ReadableStream,
...
headers: Headers,
json: json(),
...
}
where the value of response.json is the body deserializer method in the response object. You can see for yourself; try to console.log(data) from your example after removing the .json() bit, and you'll get a look at the response object in its entirety.
As you can see, the response's body - or the payload you sent from the server - is received by the client as a ReadableStream object, which then needs to be deserialized once the entire object has reached the client. The response.json() method simply deserializes the response.body ReadableStream object from serialized byte data into JSON, which you can then parse in your application.
I am passing uploaded file and dataObject in FormData:
let data = new FormData();
data.append("file", this.state.files);
data.append("data", formData);
formData is just a Json Object eg: formData = { "a":123 }
Passing data to the node server using put request with axios ,I am able to get the file object and data in req, but in data field it's giving '[object Object]'
Don't know how to access this. I tried JSON.parse(req.body.data), but getting error
SyntaxError: Unexpected token o in JSON at position 1
Looks like formData is an object that's cast to string [object Object] prior to being sent on the wire. Try data.append("data", JSON.stringify(formData)).
Send the object with JSON.stringify and then use JSON.parse once you receive data, to make the string object an object again.
I am using javascript. The following is object from jax response,
{"readyState":4,"responseText":"\r\nsuccess","status":200,"statusText":"OK"}
and my code is,
complete: function(data)
{
//console.log(data);
var result_act = JSON.stringify(data);
alert(result_act);//returning above object
var resp = result_act.responseText;//Returning undefined
}
now i want to get the responseText from this object. Any help much appreciated!
Instead of JSON.stringify you need JSON.parse
parse will parse the incoming JSON string into appropriate Javascript object. stringify is the opposite action - Javascript object into JSON valid string.
// When your server response comes with full qualified parsed JSON, it may access without any parsing.
var data, resp;
data = {"readyState":4,"responseText":"\r\nsuccess","status":200,"statusText":"OK"};
resp = data.responseText;
console.log("Response as JSON object >",resp);
// When your server response comes with JSON as string, then you require to first parse then you may allows to access.
data = '{\"readyState\":4,\"responseText\":\"\\r\\nsuccess\",\"status\":200,\"statusText\":\"OK\"}';
data = JSON.parse(data);
resp = data.responseText;
console.log("Response after parsing JSON >",resp);
I am trying to access the 'items' array in a response I get using the 'get' function in the 'request' node module. As you can see below I get the entire response and can log it to the console, but when I try to access the 'items' property within that response it says it's undefined:
console.log("r.body: " + r.body);
response:r.body: {"limit":-1,"totalCount":1,"items":[{"id":1958,"status":"PULLED"...
console.log("r.body: " + r.body.items);j
response: undefined
To avoid parsing the response each time (JSON.parse(response.body)) you can use the defaults method to tell the request module to always parse the JSON. like so:
var req = request.defaults({
json: true
})
This is useful if you are repeatedly communicating with an API.
I am trying to do a simple API call that returns an array. I believe I am successfully making the call, but the data is in the form of a cors type response object and I can't figure out where the data actually is or how to access it.
var React = require('react');
fetch('https://fcctop100.herokuapp.com/api/fccusers/top/recent', {
method: 'get'
}).then(function(data) {
console.log(data);
}).catch(function(error) {
console.log(error);
});
When I type the url into the browser, the first part of the array is like this:
[{"username":"sjames1958gm","img":"https://avatars.githubusercontent.com/u/4639625?v=3","alltime":4401,"recent":528,"lastUpdate":"2016-12-06T16:10:35.053Z"},{"username":"diomed","img":"https://avatars.githubusercontent.com/u/72777?v=3","alltime":1524,"recent":482,"lastUpdate":"2016-12-03T21:57:45.952Z"},
So I assumed that I could do data[0].username but data[0] is undefined.
The actual object return looks a little like this: Response {type:cors, url:, status:, proto, etc}