Response.data how to get a single data value - javascript

Here is the code that im using to try get a single element out of the data.response of an api:
client.on("message", msg => {
var axios = require("axios").default;
var options = {
method: 'GET',
url: 'https://dad-jokes.p.rapidapi.com/random/joke',
headers: {
'X-RapidAPI-Host': 'dad-jokes.p.rapidapi.com',
'X-RapidAPI-Key': '0f787e5af5msh468814e0b585173p1cacafjsn7d774dfb44ff'
}
};
if(msg.content === "daddy"){
axios.request(options).then(function (response) {
console.log(response.data);
let dataDad = response.body
msg.channel.send(`${dataDad}`)
})`
and here is the response that i get from the api:
{
success: true,
body: [
{
_id: '60dd3729df8a37528bc79b03',
setup: 'How often do scientists check the table of elements?',
punchline: 'Periodically',
type: 'periodical',
likes: [],
author: [Object],
approved: true,
date: 1618108661,
NSFW: false
}
]
}
How do I use the "setup" from the response data in my code at msg.channel.send( "the "setup" ) ?

I believe, You need to do response.data.body[0].setup in order to get the first objects setup property
msg.channel.send(response.data.body[0].setup);

response.data.body is an array of objects. So, if you want to access the first object in that array, you would use response.data.body[0] So, to get the .setup property from that object, you would use this:
msg.channel.send(response.data.body[0].setup);
That will get you the setup property from the first object in the response.data.body array.

Related

how to convert an array to a array of objects with additional information in react using map when doing a POST api request

I'm new with react and I'm stuck at a problem, kindly help me.
array looks like this:
surveyors=[jj,kk]
The length of array can be variable i.e.there can be more values.
what i want to send in post api is:
data:[
{
name:"kk",
is_active:True,
company:26
},
{
name: "jj",
is_active:True,
company:26
}
]
I'm using postapi like this:
const postURL = moduleURL("url");
requests({
method: "post",
url: postURL,
data: [
{
name:"kk",
is_active:True,
company:26
},
{
name: "jj",
is_active:True,
company:26
}
],
})
.then((response) => {
console.log(response);
})
.catch((err) => console.log(err));
}
if there was a fixed data i could do it but since the data in array surveyor is variable i cannot fix it.
note- company here is the company id that i have stored in a variable and it will be same for every object in array and is_active will always be true.
var supervisor=["jj","kk"];
var result = supervisor.map(s => {return {name: s, is_active:true, company:26} });
console.log(result)
use map to create a new array of objects with extra attributes;
const supervisors = ["jj", "kk"];
const modifiedSupervisors = supervisors.map(item => ({name: item, is_active:true, company:26}));
now you can use this data in api call data: modifiedSupervisors,

How to get object array generated by axios get

(async() =>{
const axios= require('axios');
const response = await axios("https://graph.facebook.com/v13.0/110524034851999/feed?limit=3&access_token=×××××××");
const data = response.data;
console.log(data);
console.log(data[0]);
})();
Above is the code I am using to get json from Facebook API I am getting an object as below
data: [
{
created_time: '2022-04-14T14:01:45+0000',
message: 'How to make jw',
id: '...'
},
{
created_time: '2022-04-14T14:01:19+0000',
message: 'Testing',
id: '....'
},
{
created_time: '2022-04-14T01:51:41+0000',
message: 'Enriqueta',
id: '.....'
}
],
I am not able to get the data from object using data[0] which should return me first object but it's giving me undefined error how can I get the message which is on first array of data object from the above json?
replace
console.log(data[0]);
with
console.log(data.data[0]);
maybe?

Making a POST request to an API in JavaScript/jQuery

I've been trying to get a POST request from an API, and I'm not having that much luck in pushing it through. I'm wondering if it's because one of the parameters I'm passing is an array of objects. Been trying to get this to work for a few hours with no luck.
This post function requires two parameters, userId and classId.
//here's the api I'm calling, obviously not the actual URL
let apisource = www.exampleapi.com
//this is the class
let classId = 12345;
//these are students in the class
let userArray = [{
"name": "user1",
"userId": 101
}, {
"name": "user2",
"userId": 102
}]
I'm writing a function that takes this userArray and matches it up to a class that contains the userIds.
Here's my API call so far:
function getStudents(classId, userArray) {
$.post(apisource) + "classes"), {
userId: userArray.userId,
classId: classId
}, function(data, status) {
console.log("students in class loaded)
}
}
Nothing ever loads. Anyone have any suggestions or pointers for something I might be doing wrong?
There are a few issues here.
For example:
userArray.userId
This part of the code is definitively invalid. Arrays have indexes, not keys like objects, for example. This means you cannot access the userId param, as you haven't defined in which index it is.
Considering your array has two items:
let userArray = [
{ name: 'user1', userId: 101 }, // index 0
{ name: 'user2', userId: 102 } // index 1
];
You would need to access the user id in the following fashion:
userArray[0].userId // Returns 101
userArray[1].userId // Returns 102
As for the request itself, it could look like something like this:
let apisource = www.exampleapi.com;
let classId = 12345;
$.ajax({
type: 'POST',
url: apisource,
data: JSON.stringify({ userId: userArray[0].userId, classId: classId }),
contentType: "application/json"
});
Fist of all, you cant access to userId property of the userArray, you need to pick the object first like "userArray[0].userId" or any logic to get one element.
In other hand, i recommed you to use the fetch function, is easier to use and the code look more clean with promise.
var apisource = 'https://example.com/';
var data = {}; // the user picked
fetch(apisource , {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // data can be `string` or {object}!
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
source: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
It looks like you need to refactor your post implementation this way to avoid some syntax errors.
function getStudents(classId, userArray) {
$.post( apisource + "classes", {
userId: userArray.userId,
classId: classId
})
.done(function( data, status ) {
console.log("students in class loaded")
});
}

How to get object in queryparams using Typescript?

In a button click i have function as,
inviewMockupEvent(data) {
console.log(data);
this.router.navigate(['/page-mockup'], { queryParams: { data: data }, skipLocationChange: true });
}
console.log(data) give the result as {mockup_id: "123", project_id: "456", module_id: "678", release_id: "890", requirement_id: "432", …}
In navigated component i am getting the data as follows,
ngOnInit() {
this.activatedRoute.queryParams.subscribe(params => {
let data = params['data'];
console.log(data);
console.log(JSON.stringify(data));
});
Where,
console.log(data) gives output as [object Object]
console.log(JSON.stringify(data)) gives output as "[object Object]"
And also,
console.log(data.mockup_id) gives result undefined
Here i need to retrieve the object values, but unable to get it.
Kindly help me to retrieve the data through query params and fetch using typescript ngOnit without using html.
You're adding an useless layer to your object. Spread it.
this.router.navigate(['/page-mockup'], { queryParams: { ...data }, skipLocationChange: true });
If you want to use the array notation, then use the array variable, not the map variable.
Display the correct variables.
this.activatedRoute.queryParams.subscribe(params => {
let data = params;
console.log(data.mockup_id);
});
Stackblitz
Base on your url localhost:80000/#/page-mockup?data=%5Bobject%20Object%5D, reason because angular picks only the data key and and converted the value into a string (I guess this is only for object values), which is why you get [object Object]
console.log({mockup_id: "123", project_id: "456", module_id: "678", release_id: "890", requirement_id: "432"}.toString());
So convert this
this.router.navigate(['/page-mockup'], { queryParams: { data: data }, skipLocationChange: true });
to this
this.router.navigate(['/page-mockup'], { queryParams: data, skipLocationChange: true });
edit(pedido : Pedido, sku:string){
this.router.navigate(['/orders/d/nuevo/editarLinea',this.id, sku, this.llamada],
{queryParams: {pedido: JSON.stringify(pedido)}}).then(r => 1 ==1);}
and read the object:
this.ruta.queryParams.subscribe(params => {
this.pedidos = JSON.parse(params['pedido']) as Pedido
});
:-)

Define API GATEWAY list type parameter

According to the aws docs it is possible to pass query parameter with list type in a format foo=1,2,3
But when I am doing it in that way i receive string instead of array in lambda event.queryStringParameters.foo === '1,2,3'
Am I missing something, or aws does not support this?
Sorry I don't have enough rep to comment yet so having to submit this as an answer.
There appears to be a new Lambda event field "multiValueQueryStringParameters".
For example the following url would generate this event in AWS Lambda:
https://example.uk/API/search?excludeLabels=sstc&excludeLabels=empty&excludeLabels=removed&limit=500
{
"resource": "/{proxy+}",
"path": "/API/search",
"httpMethod": "GET",
"headers": {},
"multiValueHeaders": {},
"queryStringParameters": {
"excludeLabels": "removed",
"limit": "500"
},
"multiValueQueryStringParameters": {
"excludeLabels": [
"sstc",
"empty",
"removed"
],
"limit": [
"500"
]
},
"pathParameters": {
"proxy": "search"
},
"stageVariables": {},
"requestContext": {},
"body": null,
"isBase64Encoded": false
}
Note that the field "queryStringParameters" only contains the last value.
You can quite easily handle both via the urijs library:
module.exports.handler = async (event, context) => {
const { path, queryStringParameters, multiValueQueryStringParameters } = event;
const uriPath = new URI(path);
if (queryStringParameters) {
uriPath.query(queryStringParameters);
}
if (multiValueQueryStringParameters) {
uriPath.query(multiValueQueryStringParameters);
}
// -- snip bootstrap of HAPI server --
// map lambda event to hapi request
const options = {
credentials: event.requestContext.authorizer,
headers,
method: event.httpMethod,
payload: event.body,
url: uriPath.toString(),
validate: false,
};
const res = await hapiServer.inject(options);
return {
statusCode: res.statusCode,
headers: res.headers,
body:
typeof res.result === 'string' ? res.result : JSON.stringify(res.result),
};
}
After some logging seems that API GATEWAY parses same query keys as a list in event.multiValueQueryStringParameters
So, if you make a request
GET https://execute-api.eu-central-1.amazonaws.com/stage/foo?bar=1&bar=2&bar=3
It will appear in event.multiValueQueryStringParameters as an array

Categories

Resources