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.
Related
I have this code
res.cookie("jid", token, {
httpOnly: false,
path: "/",
});
console.log("cookee is : ",res.cookie.name);// cokkie name not accessible
console.log("cookee is : ",req.cookies); // here it is accessible
So i am surprised that i set cookiee in res object but i was not able to access it throuhg res object but i was able to access it throug req object.
You can find the source code for res.cookie() here.
You can see that in the end, it calls this.append('Set-Header', ...), which adds a header to the response.
The Express response inherits from Node's ServerResponse, so the API to access the headers set on a response is res.getHeader().
So:
res.cookie("jid", ...);
console.log(res.getHeader('set-cookie'));
may do part of what you want here.
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 want to know how to access object response properties from a ajax call, i'm working with laravel 5.2 and Ajax, and i have this one:
$.get('/provider/'+provider_id+'', function(response){
console.log(response);
});
Yeah i tried with response = JSON.parse(response);but i got this error Uncaught SyntaxError: Unexpected token o in JSON at position 1(…) what's wrong?? or how i should to do? thanks!
As you can see from the console output, response is already an Object. No need to parse it again.
$.get('/provider/' + provider_id, function(response){
var data = response.response;
console.log("Email: " + data.email_p);
});
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}
I list videos in a playlist with the javascript client api like this:
var request = gapi.client.youtube.playlistItems.list(options);
request.execute(function(response) {
---
It works fine, but sometimes response is undefined for the same query. Can response legitimately be undefined here or is it a bug?
According to this it cannot be undefined, at most false, but it should not be false, because the response should be a json object in this case:
The callback function which executes when the request succeeds or
fails. jsonResp contains the response parsed as JSON. If the response
is not JSON, this field will be false. rawResp is the HTTP response.
It is JSON, and can be parsed to an object which includes body,
headers, status, and statusText fields.
https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiclientHttpRequest
So is it an occasionally appearing bug to be fixed or should I be prepared for response being undefined here in the production app?