Axios sends an array of strings instead of an array of objects - javascript

Axios sends an array of strings instead of an array of objects. I have an array of objects that contains data about the event. I'm trying to send a request to the server via axios, but I get a array of strings insteenter image description heread of objects at the output
let data = {
title: 'Game',
subject: 'Some subject',
date: ['01/01/2021','01/01/2021'],
years: ['1970', '1970'],
address: 'None',
ages: [
{
title: 'Men',
weights: [{page: 0, title: '60'}]
}
]
};
api.Create({
params: data
}).then(function (response) {
console.log(response.data);
})
.catch(function (err) {
console.log(err);
});
api response

try to:
console.log(JSON.parse(response.data))
What you get back from the server is string. you need to parse it.
When you send data to and from a server, it is sent as a 'serialized' string, usually JSON format
That's how server responses work

It turned out to be an incorrect request. I used GET to pass the object, instead of POST, so it converts it to a string. I want to notice that there is an evil community on this site.

Related

How to retrieve array value in Node.js and send to next calling API

I am new to I have a JSON response from an API , which I need to parse two values in the JSON and then pass those value to the next API. The challenge I have is , I will have N number of Array JSON response similar to the sample I am Showing below ,this is one sample json but there will be n number of json concatenated of the same structure.
Now I want to retrieve the id and messages.messageId value within customers object and pass the same as input to next API call. How could I retrieve the matching id and message id and save it in a list to send to next API
"id":"64146c29",
"Customers":[
{
"id":"4a61aaf2-c6bc-41ae-9ecd-041825135bf5",
"startTime":"2022-11-29T16:00:07.623Z",
"endTime":"2022-11-29T16:00:07.630Z",
"attributes":{
"contactId":"30000236925961000-B1"
},
"provider":"Beta",
"peer":"7126e24c-affa-4fb8-a450-50a644764a32",
"messages":[
{
"messageId":"ce67fba0ef44523f0d9a9d5dd5649642"
}
],
"type":"sms",
"recipientCountry":"US",
"recipientType":"mobile"
},
{
"id":"bbed4f9c-1be7-4fe5-ba37-5e058e9f16c6",
"startTime":"2022-11-29T16:00:07.626Z",
"endTime":"2022-11-29T16:00:07.668Z",
"attributes":{
},
"provider":"Beta",
"peer":"fe49dd4a-012e-447b-b9fe-7667678756c7",
"messages":[
],
"type":"sms",
"recipientCountry":"US",
"recipientType":"tollfree"
}
],
"otherMediaUris":[
],
"selfUri":"64146c29-fe0d-4482-935e-8b86be878cb9"
} ````
To get this data (id and messageId) of each customer, you will have to loop over the customers array and return those value from each customer object.
const customersDataToSendToApi = customersDataFromApi.Customers.map(customer => {
return {customer.Id, customer.messages.messageId}
})
The customersDataToSendToApi is already an array which you can pass in the body of API POST request. I hope this helps.
Yes, you do the same thing to the array of multiple json since you say they have similar structure.
arrayOfMultipleJson.map(eachJson =>{
eachJson.Customers.map(customer => {
return {customer.Id, customer.messages.messageId}
})
})
Do you get the picture I am painting?
If you don't mind me asking, what scenario makes you get multiple JSON in one API call?

Iterate over JSON data in JavaScript

I am working on some trains' open data feed and getting some JSON as a response from a server. I parse this JSON into a data variable and display it as seen below. However, I cannot find a way to iterate over the response to be able to manipulate each message. I want to iterate over each message and then use the data for a record in a SQL database. I cannot get to the point of accessing any individual message data.
How can I create a loop to iterate over each message and extract it's data?
[
{
SF_MSG: {
time: '1666370311000',
area_id: 'TD',
address: '0C',
msg_type: 'SF',
data: '1F'
}
},
{
CA_MSG: {
to: '4333',
time: '1666370311000',
area_id: 'WO',
msg_type: 'CA',
from: '4331',
descr: '2K60'
}
}, ...
]
Edit: using data.forEach(function(message) produces an output of the structure:
{ CA_MSG: { to: '6021', time: '1666372120000', area_id: 'CY', msg_type: 'CA', from: 'STIN', descr: '2Y73' } }
, however, how do I query this inner object, the names of the objects will differ depending on message type if this matters?
try this:
data = JSON.parse(yourJSONdata)
data.map((o, i)=>{
//o is the object, i is the index
// do your processing here
then at the end do
data[i]=processedobject
})

Is this a correct api response?

I'm trying to learn about API's and am creating a simple response when a user hit's an endpoint on my basic express app.
I'm not sure what constitutes a correct API response though, does it need to be an object?
The data I was given is an array of arrays and I export it from a file and return it in the express app as an object using response.json(), it displays ok but I'm not sure if I'm following the right approach for how I'm handling it and displaying it.
I would like to understand how should API data be returned, I had the feeling that it should always be an object but what I'm returning here is an array of arrays, some explanation to understand this better would be helpful please.
Here is my data file:
export const data = [
[
'a9e9c933-eda2-4f45-92c0-33d6c1b495d8',
{
title: 'The Testaments',
price: { currencyCode: 'GBP', amount: '10.00' },
},
],
[
'c1e435ad-f32b-4b6d-a3d4-bb6897eaa9ce',
{
title: 'Half a World Away',
price: { currencyCode: 'GBP', amount: '9.35' },
},
],
[
'48d17256-b109-4129-9274-0bff8b2db2d2',
{ title: 'Echo Burning', price: { currencyCode: 'GBP', amount: '29.84' } },
],
[
'df2555ad-7dc2-4b1f-b422-766184b5c925',
{
title: ' The Institute',
price: { currencyCode: 'GBP', amount: '10.99' },
},
],
];
Here is a snippet from my express app file which imports the data object for this endpoint:
app.get('/books', (request, response) => {
response.json({ books: data });
});
Looks okay, one thing I would do is ensure the root of the object you return always has the same name between api calls, so here your root object name is "books":
app.get('/books', (request, response) => {
response.json({ books: data });
});
I would personally change this to something like:
app.get('/books', (request, response) => {
response.json({ data: data });
});
Now that may seem confusing, but what that means is when your api is queried, the actual resources the api is returning is always in an object called data, it just builds a common pattern for where people should be expecting to see the api response resources in your JSON response.
So if you had another endpoint for authors for example, people will know the authors response will be under an object called data:
app.get('/authors', (request, response) => {
response.json({ data: authors });
});

Send object as get parameter with Axios

The API expects the following GET request:
/resource?labels[team1]=corona&labels[team2]=virus
My issue is to generate this URL using the Axios params option.
I tried the following params structures and they both generate the wrong url:
{
labels: {
team1: 'corona',
team2: 'virus'
}
}
{
labels: [
team1: 'corona',
team2: 'virus'
]
}
I at least thought it would work with the string indexed array but that generates no get params at all.
So, can anyone tell me how to generate the desired URL?
The solution was to use the paramsSerializer with the same setup as in the axios readme. And I used the first params object from my post above..
paramsSerializer: (params) => {
return qs.stringify(params, { arrayFormat: 'brackets' });
}

How to emit object using socket.io?

I have a code like, I have a problem with sending response.
socket.on('findUserMessages', (userName) => {
io.sockets.connected[socket.id].emit('Checking-message', {
type: 'ss',
text: bot,
user: 'bot'
});
var dupa = db.chat.find({ user: userName }, function(err, docs) {
userName = userName
if (err) throw err;
console.log('load old messages', docs)
})
io.emit('private message', dupa);
})
My node console output is like
[ { _id: 5888bdd6cef7952e38821f35,
text: 'O rajciu rajciu',
user: 'Adam',
time: 2017-01-25T15:01:42.733Z }]
I know that output is not a JSON string, how to solve that? I was trying to use .toArray() but without succes.
That might be silly question but I am stuck with it for a long time.
Convert to json your result before emitting it. Try to emit JSON.stringify(dupa).
EDIT
Your output is actually JSON already (JSON array), so if you want to get only JSON string on client side, convert your output to string there (JSON.strigify(result) on client side on receiving the emit event).

Categories