Why getting unexpected token with Twilio? - javascript

Given the sample code from Twilio:
const accountSid = 'ACf37a37065e79fb1a7a594f294cb3b190';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);
client.messages
.create({
body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
from: '+15017122661',
to: '+15558675310'
})
.then(message => console.log(message.sid));
How do you get the error code and error message?
Here's the output (as per the quickguide)
{
"account_sid": "ACf37a37065e79fb1a7a594f294cb3b190",
"api_version": "2010-04-01",
"body": "This is the ship that made the Kessel Run in fourteen parsecs?",
"date_created": "Thu, 30 Jul 2015 20:12:31 +0000",
"date_sent": "Thu, 30 Jul 2015 20:12:33 +0000",
"date_updated": "Thu, 30 Jul 2015 20:12:33 +0000",
"direction": "outbound-api",
"error_code": null,
"error_message": null,
"from": "+15017122661",
"messaging_service_sid": "MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"num_media": "0",
"num_segments": "1",
"price": -0.00750,
"price_unit": "USD",
"sid": "MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"status": "sent",
"subresource_uris": {
"media": "/2010-04-01/Accounts/ACf37a37065e79fb1a7a594f294cb3b190/Messages/SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Media.json"
},
"to": "+15558675310",
"uri": "/2010-04-01/Accounts/ACf37a37065e79fb1a7a594f294cb3b190/Messages/SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json"
}
I'm trying this:
client.messages
.create({
body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
from: '+15017122661',
to: '+15558675310'
})
.then(message => console.log(message.sid));
.then(message => console.log(message.error_code));
But doesn't work. I get unexpected token.
Ideally I want to log the error code and message and other information like date_sent, etc.. so I validate and send the right info back to the client.
Any help will be greatly appreciated.
thanks

You're getting the token thing because you have a semicolon between the two then() (observe the end of the first line and the beginning of the second line in code below)
.then(message => console.log(message.sid)); // <----
.then(message => console.log(message.error_code));
So, try something like this:
client.messages
.create({
body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
from: '+15017122661',
to: '+15558675310'
})
.then(message => {
console.log(message.sid);
console.log(message.error_code || 'no error');
});

Related

How to extract a value from a JSON document with JS

i´n very new working with JSON, and JS, so i got a problem, I´m trying to get the value inside the object attachments[{path = "..."}], but i get multiple errors due I don´t really know how to do it.
This is my JSON:
[{ "from": [{ "address": "luis#gmail.com", "name": "Luis " }], "date": "2022-06-16T14:01:08.000Z", "receivedDate": "2022-06-16T14:01:26.000Z", "to": [{ "address": "luis.#ton.edu.co", "name": "" }], "subject": "Facturacion electronica", "text": "\n", "textPlain": "\n", "hasAttachment": true, "original": { "body": "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" /><div dir=\"ltr\"><div class=\"gmail_default\" style=\"font-family:arial,helvetica,sans-serif;font-size:large\"><br></div></div>\n", "headers": { "received": ["from DM5PR1301MB2218.namprd13.prod.outlook.com (2603:10b6:4:30::30) by MN2PR13MB3693.namprd13.prod.outlook.com with HTTPS; Thu, 16 Jun 2022 14:01:26 +0000", "from SN4PR0201CA0046.namprd02.prod.outlook.com (2603:10b6:803:2e::32) by DM5PR1301MB2218.namprd13.prod.outlook.com (2603:10b6:4:30::30) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.5353.11; Thu, 16 Jun 2022 14:01:23 +0000", "from SN1NAM02FT0046.eop-nam02.prod.protection.outlook.com (2603:10b6:803:2e:cafe::73) by SN4PR0201CA0046.outlook.office365.com (2603:10b6:803:2e::32) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.5353.14 via Frontend Transport; Thu, 16 Jun 2022 14:01:23 +0000", "from mail-pg1-f182.google.com (209.85.215.182) by SN1NAM02FT0046.mail.protection.outlook.com (10.97.5.4) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.5353.14 via Frontend Transport; Thu, 16 Jun 2022 14:01:22 +0000", "by mail-pg1-f182.google.com with SMTP id d129so1314505pgc.9 for <luis.villalba.9677#miremington.edu.co>; Thu, 16 Jun 2022 07:01:22 -0700 (PDT)"], "authentication-results": "spf=pass (sender IP is 209.85.215.182) smtp.mailfrom=gmail.com; dkim=pass (signature was verified) header.d=gmail.com;dmarc=pass action=none header.from=gmail.com;compauth=pass reason=100", "received-spf": "Pass (protection.outlook.com: domain of gmail.com designates 209.85.215.182 as permitted sender) receiver=protection.outlook.com; client-ip=209.85.215.182; helo=mail-pg1-f182.google.com; pr=C", "dkim-signature": "v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112; h=mime-version:from:date:message-id:subject:to; bh=vQCl0MdNDi0YVPYmwIcLob2sZQ71Mebd3Yrxzhr2nV8=; b=hOasXO3PARCRh6q+OUeBy9jgqQMeCXFnFtqECYaqBHWLIMMEhmsEASC3TgBGD/e2aT ssZZWLPMebxtvH/MlywEDSpAT7XIaEPdng94OXrUeIFc3LeGwxc9XYpVqM4AYn3fIGko cxP9anbIq+X4a0wP5h8QZha4lR4ljPlsVFwk9vNMeEsjxcvdpeUR0wgFo2S5jLYx6dIp UoNKHM5+jtcYLvIozU9Jyo0SjZhTy6HjEQGBgLCq2qgliCsrJdr2U2jg1KvMfgCwe/ML sfsyCxxicz3k5vd7alNEui1sbCEvNw8NnKjOyuXygKQo3DOvDrR3sO4DGOpjaJTMUjlt nqsA==", "x-google-dkim-signature": "v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=x-gm-message-state:mime-version:from:date:message-id:subject:to; bh=vQCl0MdNDi0YVPYmwIcLob2sZQ71Mebd3Yrxzhr2nV8=; b=CDJrrRsU7P8GE+Wt91DoNru2dF7J2CBccSM7ST/dy+N7DJ3laHstwWF4qGcc/jdHXb yKDcUnA8tEH+SAlI+qMSVh2w60uyT7kVMKqMp9Pxf6oUj3ARanktSic0aZcVr/HN9kfh cu4FcU8AlUl+dSNg+dQ8fbmjvinuiMk1o2NG08HiXq9H5NQDMrss70sU7LA+yHqp0j9r +FrpsyAPlki58Kfj7MonmoqBSm9P5MCxVDRDp/N8lz0KCpMor5mXIUsb3Qb0F9YY97Ly 1Dfu31FmBSD2iVcYQ73xyEcpFNLRk22PiHHfBjmtkggRm5HvcPeqE8irblzRSP5zQoLX RAVw==", "x-gm-message-state": "AJIora+bCFuSkz5hlTY5ZdIyetiVpD0KGMzS4fcKCNGoEhA2qgQ9vp1G LtSF7qtu89FIJkcLfM3fasLPL8YL2M8KURKW5DCFUgbcurU=", "x-google-smtp-source": "AGRyM1vNXatnK7wAXbgyqbI4O/wuFK+BQ3cfP1jz3ra3mzWl/22XO5Q4YDaFGEZ4aq0pRFI/bFjqHnOWBWd1NauKNfo=", "x-received": "by 2002:a63:1b53:0:b0:3fd:168e:d9a with SMTP id b19-20020a631b53000000b003fd168e0d9amr4681929pgm.617.1655388081210; Thu, 16 Jun 2022 07:01:21 -0700 (PDT)", "from": "Luis <luis#gmail.com>", "date": "Thu, 16 Jun 2022 09:01:08 -0500", "message-id": "<CAL0BCDnijtvACn6Y408hX6+XDRih6zKg+td6digWxcT7khWrBA#mail.gmail.com>", "subject": "Facturacion electronica", "to": "luis#ton.edu.co", "content-type": "multipart/mixed; boundary=\"0000000000008bea1805e191122e\"", "return-path": "luis#gmail.com", "x-ms-exchange-organization-expirationstarttime": "16 Jun 2022 14:01:22.8465 (UTC)", "x-ms-exchange-organization-expirationstarttimereason": "OriginalSubmit", "x-ms-exchange-organization-expirationinterval": "1:00:00:00.0000000", "x-ms-exchange-organization-expirationintervalreason": "OriginalSubmit", "x-ms-exchange-organization-network-message-id": "08cd21ef-317f-4b77-cff7-08da4fa0b224", "x-eopattributedmessage": "0", "x-eoptenantattributedmessage": "3855fd0e-2e9a-4fcc-9552-878a0fe4a05d:0", "x-ms-exchange-organization-messagedirectionality": "Incoming", "x-ms-publictraffictype": "Email", "x-ms-exchange-organization-authsource": "SN1NAM02FT0046.eop-nam02.prod.protection.outlook.com", "x-ms-exchange-organization-authas": "Anonymous", "x-ms-office365-filtering-correlation-id": "08cd21ef-317f-4b77-cff7-08da4fa0b224", "x-ms-traffictypediagnostic": "DM5PR1301MB2218:EE_", "x-ms-exchange-organization-scl": "1", "x-microsoft-antispam": "BCL:0;", "x-forefront-antispam-report": "CIP:209.85.215.182;CTRY:US;LANG:es;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:mail-pg1-f182.google.com;PTR:mail-pg1-f182.google.com;CAT:NONE;SFS:(13230016)(84050400002)(42186006)(1096003)(4006050)(6916009)(5660300002)(76482006)(356005)(7636003)(21480400003)(8676002)(86362001)(7596003)(7116003)(21470400002)(75640400001)(73392003)(55446002)(33964004)(26005)(336012)(82202003)(3480700007)(6666004)(564344004)(563144003);DIR:INB;", "x-ms-exchange-crosstenant-originalarrivaltime": "16 Jun 2022 14:01:22.7840 (UTC)", "x-ms-exchange-crosstenant-network-message-id": "08cd21ef-317f-4b77-cff7-08da4fa0b224", "x-ms-exchange-crosstenant-id": "3855fd0e-2e9a-4fcc-9552-878a0fe4a05d", "x-ms-exchange-crosstenant-authsource": "SN1NAM02FT0046.eop-nam02.prod.protection.outlook.com", "x-ms-exchange-crosstenant-authas": "Anonymous", "x-ms-exchange-crosstenant-fromentityheader": "Internet", "x-ms-exchange-transport-crosstenantheadersstamped": "DM5PR1301MB2218", "x-ms-exchange-transport-endtoendlatency": "00:00:03.4778129", "x-ms-exchange-processed-by-bccfoldering": "15.20.5353.014", "x-microsoft-antispam-mailbox-delivery": "ucf:0;jmr:0;auth:0;dest:I;ENG:(910001)(944506458)(944626604)(920097)(930097);", "x-microsoft-antispam-message-info": "rheidSJ3gyr1XepOaJ17S9LjRMc9FjOc8VPhMFGDvlLrCoHayxpaJN2Xe+/79unbyGbEPqNlKy+ouyW/kWiWbMjtkimlHzHZDBB3456/JLb3xkUdbuBmNwBvLvuPQ+9nqW1c1q9zHryvsGAAWnzn0CS8CZAziQjbABYTxkKLPDe0K0vTh+Un0e3x+kQgveI8CQE9UPgejQn8lAtcPD0DcAt6OB92NrlcEGlG7oEuPkTrZg1P5zVFaN/mC1F1FC0uujUcq/qCjV6wRWiN+5xRDpwMuJBdWCxL33+K05dXAt34tEDcwEy/y2DGgwsGPU6vVSnLee6M3zoJ9S4Uj02MsengV4UD80Yex2ETnr/jaq9axK/zAWCX4TTa9joBF998NhCewoerqVS7Quq+4PkYkNmaB1Cqw8SCOCNE+sktY+0E8caKjGs9/3+AttiVzj6XK1kr7cz/2M/ub9e4zALY+OxDTY4L5oxv73wH0TY9EjTc7nEFyjLe8GYM3RQ0zcIaSGKDKHv2QBqYcQgH866End0ScFqTKSAqMGez2SxF4AblBQjpLxbuIrWre1k/+JkiCrqWhlNcdOyxgrLksANeyTsT41L8uRXNqCzqc99JPqYm+j+4b1FHDhC9QDhY9aCx+A/OkvxY2+6EpvYF911eroNYTV/JEWL0bRhDIn86VY65QdfjgBRKASVTHbyMFVMjKppXK3NaP4bt2WZZuk4ucxTjdlcS5e0+MFz1zviXwXp86JCCJOcBGdbPjo2rSzvJsKhckhXzPX+A7K39FBLTDYbQYxnPp15gRTLGH/J9ani1CUCxP3AWwHnwnQp5zzD0Gqn2Gf164Pnsrnc7rCYr/6Ohj8nr8RAMpTcmj0MRJLM5cj0G12Y5sYmeg49KY5bqH4Ouo8+IqXtYNzweNRe1uA0BGbf7EzbfHxjavfrzY7tdJn4cXdfjtAxKq+SNdHBOz7yufUjGeNNglrNqk4ednOsBUD3C2Tr/NlUG1H59j/sXUc6RD9eS6D+Jf+4vz5b6cHxefgW6fCa6H9P2UxdUf6++rpZgIhL9EkmZCEahnfxc9xYMpBFavIz1S5HvCfLmZhTBo1HR48NCHMoUC1hmZ7fUsPOAsR8hLyLLnhC9l5/IJmblBHn1Im7TvQyhReiyysKN4sYy29KIuhlwujihAKK6GpjyMU3A1NSATiL870pMy3RCIn3FbdphADYbjLuG1sUwi47eO3lF8w6NRo91YlTEM32F5wi9YKFTp/eh2RYnbH0KAijFImSbEHCL58EGjcK5iq08l7qLyYjgrMdgR7mL5EDaWJw3rziHgzxbU7ETA8PKUt3sOIJ1iGGFQvhzdGO+saxN7GD9WzMmf+Jjp2pQ3Jgcidg52/5gIBogmrCc6WtCrXrqBbmYipu2vhsn73cd5RWJNUltifwlnL3v3QSXRyx6xiExI5IF6j7dn1fBn2jDLcEZWc5D1WPajgGu9y2ZWYXzblwya8ZY0RW28qBWuxqjkOf34tF6hJTaXcSlbg7936dtoor2WA6Cd0CUDuShP+vny9uOcXWQk6Oh59gxc56pk3rZoWGQ4tCK5q0=", "mime-version": "1.0" } }, "uid": "2243", "attachments": [{ "path": "C:\\Users\\usuario\\Desktop\\ioio\\Proyectos\\ioio\\2022-06-16\\1655388696749.oioio.zip" }] }]
The attachments part, is at the end of the JSON, and this is what I´m trying from JS
const jsonData = require('./prueba.json');
var strngJson = JSON.parse(JSON.stringify(jsonData))
console.log(strngJson)
console.log(jsonData.attachments.path);
//console.log(data.attachments.path[0]);
As i said, i´m really new with JS; son any explanation on how it will work, will be really appreciate it! Thanks a lot
I think your problem is that you are getting an array from that json and then you have the same problem again, I mean the attachments is another array.
So you will have to do the following:
const jsonData = require("./prueba.json");
var strngJson = JSON.parse(JSON.stringify(jsonData));
console.log(strngJson);
console.log(strngJson[0].attachments[0].path);

How to print date label once in Javascript

I am building a chat application using vueJs and I would like to display date labels just like whats app.
Messages are received in following format on client side
{
{
author: 21,
created_at: "12:09 pm",
data: "chat message",
message_group: "today",
type: "text"
},
{
author: 22,
created_at: "11:30 pm",
data: "chat message 2",
message_group: "today",
type: "text"
},
{
author: 22,
created_at: "11:29 pm",
data: "chat message 3",
message_group: "yesterday",
type: "text"
}
}
How do I print messages in following format.
Yesterday
Chat Message 3
Today
Chat Message 2
Chat Message
How can I do it without grouping the array?
Thank you
Can't do it in the comment up there so putting it as an answer.
You can have a computed property or getter (vuex) to get the day labels without grouping as below
// Do your sorting first
computed: {
dayLabels() {
return a.reduce((acc, message) => {
if (!acc.includes(message.message_group)) {
acc.push(message.message_group);
}
return acc;
}, []);
}
}

Zapier Results from `triggers.new_booking.operation.perform` must be an array of objects

I am building a zapier integration for an app. The app returns a JSON response like this...
{
result: "Success",
message: "Showing a total of 1 bookings",
bookings: {
42: {
event: {
event_name: "Chris's Event",
event_date_uk: "Saturday 22nd Jun 2019"
}
}
}
}
In my zapier parser, I have the following....
const options = {
url: bundle.authData.url+`/api/v1/bookings`,
method: 'GET',
headers: {
'Accept': 'application/json'
},
params: {
'key': bundle.authData.api_key,
'secret': bundle.authData.client_secret,
'booking_id': 42,
'scope': 'full'
},
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = z.JSON.parse(response.content);
return results["bookings"];
});
However, when I test, I get the following....
Results from triggers.new_booking.operation.perform must be an array of objects. We got {"42": {"event": {"event_name": "Chris's Event", "event_date_uk": "Saturday 22nd Jun 2019"}}}.
I thought JSON.parse did return an object? And from what I can see I have returned an array of objects. Any ideas what Im doing wrong?
This contains an array of objects (bookings):
{
"result": "Success",
"message": "Showing a total of 1 bookings",
"bookings": [
{
"42": {
"event": {
"event_name": "Chris's Event",
"event_date_uk": "Saturday 22nd Jun 2019"
}
}
}
]
}
Edit: To access the event property in your JSON it's bookings.42.event where in JSON above it's bookings[0].42.event.

How do I add Internet Explorer 10 support to a simple VueJs component?

I have a simple VueJs component I'm building that doesn't render at all in IE 10.
Background: The Vue component is a listing of company events, that supports basic filtering and sorting. Unfortunately, I have to support IE10. I am not using babel, but tried to use it in troubleshooting this problem - had no effect
The error I'm getting is 'city' is undefined. IE10 is the only browser experiencing this issue.
Here's a CodePen of just the relevant code. I've added comments to clarify what's going on. Here is just the JS (see CodePen for full code and better context):
/* Server rendered data */
var events = [{
path: "events/residuals-biosolids",
name: "Residuals & Biosolids Conference",
sortDate: "1536165900000",
startDate: "4 September 2018",
endDate: "5 October 2018",
displayDate: "September 4 - October 5, 2018",
state: "WI",
city: "Milwaukee",
booth: "342",
featuredImg: "https://cdn2.hubspot.net/hubfs/4299619/event%20thumb.png"
}, {
path: "events/bio-expo",
name: "Biosolid Expo",
sortDate: "1548979200000",
startDate: "6 February 2019",
endDate: "5 March 2019",
displayDate: "February 6 - March 5, 2019",
state: "MN",
city: "Eagan",
booth: "12",
featuredImg: ""
}, {
path: "events/world-ag-expo",
name: "World AG Expo",
sortDate: "1549670400000",
startDate: "7 February 2019",
endDate: "2 February 2019",
displayDate: "February 7 - 2, 2019",
state: "CA",
city: "Tulare",
booth: "3815",
featuredImg: ""
}];
var eventsDesc = [{
path: "world-ag-expo",
name: "World AG Expo",
sortDate: "1549670400000",
startDate: "7 February 2019",
endDate: "2 February 2019",
displayDate: "February 7 - 2, 2019",
state: "CA",
city: "Tulare",
booth: "3815",
featuredImg: ""
}, {
path: "bio-expo",
name: "Biosolid Expo",
sortDate: "1548979200000",
startDate: "6 February 2019",
endDate: "5 March 2019",
displayDate: "February 6 - March 5, 2019",
state: "MN",
city: "Eagan",
booth: "12",
featuredImg: ""
}, {
path: "residuals-biosolids",
name: "Residuals & Biosolids Conference",
sortDate: "1536165900000",
startDate: "4 September 2018",
endDate: "5 October 2018",
displayDate: "September 4 - October 5, 2018",
state: "WI",
city: "Milwaukee",
booth: "342",
featuredImg: "https://cdn2.hubspot.net/hub/4299619/hubfs/event%20thumb.png?width=760&name=event%20thumb.png"
}];
var selectedStates = ["CA", "MN", "WI", ];
var selectedCities = ["Eagan", "Milwaukee", "Tulare", ];
/*
Vue code below
*/
var app = new Vue({
el: "#sg-events-wrapper",
data: {
message: "Hello Vue!",
dateOrder: "ascending",
selectedCity:"none",
selectedState:"none",
/*the data below is pulled from the script tag in the page.*/
eventCities:selectedCities,
eventStates:selectedStates,
eventList: events,
eventListDesc:eventsDesc,
},
computed: {
eventsSorted:function(){
/*chooses which server generated list to use for rendering events*/
if(this.dateOrder=="ascending"){
return this.eventList;
}
else{
return this.eventListDesc;
}
},
},
methods:{
/*handles the visual filtering when someone sets city and or state*/
isInStateAndCity:function(eventsCity,eventsState){
var citiesMatch;
var statesMatch;
if(eventsCity == this.selectedCity || this.selectedCity=="none"){
citiesMatch = true;
}else{
citiesMatch = false;
}
if(eventsState == this.selectedState ||this.selectedState=="none"){
statesMatch = true;
}else{
statesMatch = false;
}
if(citiesMatch && statesMatch){
return true;
}else{
return false;
}
}
}
});
Troubleshooting steps I've tried:
Used babel, though my code originally isn't written that way.
I used the babel-polyfill - did not seem to have an effect.
I tried to place the js that's in the script tag in the body into the main JS file to see if there was an issue with the js file being loaded for some reason before the code in the HTML. Had no effect.
What I think could be causing the issue: IE10 doesn't like assigning property values to objects like I'm doing. Not certain of this. It's just a guess and I can't think of another way to do it.
Screenshot of IE 10 console error and failed rendering in CodePen in-case it helps.
If you have any ideas but don't have a way to test: I can test any changes and send back a recording of what I see and the console if it has errors.
Posting the answer myself, as others will likely come across this issue too, and there isn't much info out there.
There were two issues. My selectedCities and selectedStates arrays had a comma at the end. Newer browsers don't care about that, but <=IE10 do.
In addition there is a VueJS issue. Someone updated Vue JS to use a new regex string that IE 10 and down do not understand. The fix is to either use an older version of VueJS or replace the regex. Instructions at the source of where I found this info:
https://github.com/vuejs/vue/issues/7946#issuecomment-393713941

NodeJS: retrieving an array which is wrapped in a string

I'm currently trying to save a mail object () I'm getting back from an API into our Mongo database.
This is all fine for all values being passed accept the field 'attachments'. The attachments are supposed to be an array of objects, but this is wrapped in a string. My question now is: how do I get the array out of that string?
Example of the req.body which I'm getting from the POST request:
{ timestamp: '1538728432', token:
'0a1336769443d5a593d0ef7c1c817d29ef64ba422fc3cc45f1', signature:
'c44c67660f0ad97bbb5ece92c733302d4511d4607b5787ae6aa8f2203b0e2e3e',
domain: 'karaton.uk', From: '',
'X-Envelope-From': '', To: '',
'Dkim-Signature': 'v=1; a=rsa-sha256;
c=relaxed/relaxed;\td=karaton.be;
s=20140924;\th=content-type:subject:reply-to:from:to:message-id:mime-version:date:from;\tbh=Xfm+LiX4NVMKTRaQB7gNUXf6z8yVjUqn23aenMee/q4=;\tb=JEslFgXEsO3/kW3khZFF6F4HEo9Mwx+oXJH5DGsXALaGa98ki9o5tLddmEcClqhZ8IJLR0+vrMJ3x\t
zU5ThqHNElHpt6VE9MX5ZSHJHnI2kiEXq7MN5BUWfStlS2stYwooZcuZKOkbZXRaUHODewUQbhvZQD\t
5/eA5RltbAOqwIaA=', from: '', 'User-Agent':
'One.com webmail 27.8.5', Date: 'Fri, 05 Oct 2018 10:21:49 +0200',
'Message-Id': '<1538727709180.51726.8212#webmail12>',
'Mime-Version': '1.0', Received: [ 'from
mailrelay4-2.pub.mailoutpod1-cph3.one.com
(mailrelay4-2.pub.mailoutpod1-cph3.one.com [46.30.212.3]) by
mxa.mailgun.org with ESMTP id 5bb71f1f.7f030c2a1580-smtp-in-n02; Fri,
05 Oct 2018 08:21:51 -0000 (UTC)',
'from onecom-webmail2 94.143.189.242 (unknown [46.30.211.130])\tby mailrelay4.pub.mailoutpod1-cph3.one.com (Halon)
with ESMTPSA\tid b4d6415f-c877-11e8-86b7-d0431ea8bb10;\tFri, 05 Oct
2018 08:21:49 +0000 (UTC)' ], 'X-Halone-Cookie':
'c9ea0f7e80128b5bfaf5bf8d8aca6fced5bcb162', subject: '2
attachments', 'message-url':
'https://se.api.mailgun.net/v3/domains/karaton.uk/messages/eyJwIjpmYWxzZSwiayI6IjEyNzQ1ZmViLTM4OTItNDdkZC04MTJiLWJlYzU4ZjNjYTI4MCIsInMiOiI1NDE1ODQ0ZjIyIiwiYyI6InRhbmtiIn0=',
'Reply-To': '', recipient: 'tho#karaton.uk',
sender: 'thomas.l#karaton.be', 'X-Mailgun-Incoming': 'Yes',
'message-headers': '[["X-Mailgun-Incoming", "Yes"],
["X-Envelope-From", ""], ["Received", "from
mailrelay4-2.pub.mailoutpod1-cph3.one.com
(mailrelay4-2.pub.mailoutpod1-cph3.one.com [46.30.212.3]) by
mxa.mailgun.org with ESMTP id 5bb71f1f.7f030c2a1580-smtp-in-n02; Fri,
05 Oct 2018 08:21:51 -0000 (UTC)"], ["Dkim-Signature", "v=1;
a=rsa-sha256; c=relaxed/relaxed;\td=karaton.be;
s=20140924;\th=content-type:subject:reply-to:from:to:message-id:mime-version:date:from;\tbh=Xfm+LiX4NVMKTRaQB7gNUXf6z8yVjUqn23aenMee/q4=;\tb=JEslFgXEsO3/kW3khZFF6F4HEo9Mwx+oXJH5DGsXALaGa98ki9o5tLddmEcClqhZ8IJLR0+vrMJ3x\t
zU5ThqHNElHpt6VE9MX5ZSHJHnI2kiEXq7MN5BUWfStlS2stYwooZcuZKOkbZXRaUHODewUQbhvZQD\t
5/eA5RltbAOqwIaA="], ["X-Halone-Cookie",
"c9ea0f7e80128b5bfaf5bf8d8aca6fced5bcb162"], ["X-Halone-Id",
"b4d6415f-c877-11e8-86b7-d0431ea8bb10"], ["Received", "from
onecom-webmail2 94.143.189.242 (unknown [46.30.211.130])\tby
mailrelay4.pub.mailoutpod1-cph3.one.com (Halon) with ESMTPSA\tid
b4d6415f-c877-11e8-86b7-d0431ea8bb10;\tFri, 05 Oct 2018 08:21:49
+0000 (UTC)"], ["X-Originating-Ip", "94.143.189.242"], ["User-Agent", "One.com webmail 27.8.5"], ["Date", "Fri, 05 Oct 2018 10:21:49
+0200"], ["Mime-Version", "1.0"], ["Message-Id", "<1538727709180.51726.8212#webmail12>"], ["To", ""],
["From", ""], ["Reply-To",
""], ["Subject", "2 attachments"],
["Content-Type", "multipart/mixed;
boundary=\"----------8210-1538727709180-1\""]]', 'X-Halone-Id':
'b4d6415f-c877-11e8-86b7-d0431ea8bb10', 'Content-Type':
'multipart/mixed; boundary="----------8210-1538727709180-1"',
'X-Originating-Ip': '94.143.189.242', Subject: '2 attachments',
attachments: '[{"url":
"https://se.api.mailgun.net/v3/domains/karaton.uk/messages/eyJwIjpmYWxzZSwiayI6IjEyNzQ1ZmViLTM4OTItNDdkZC04MTJiLWJlYzU4ZjNjYTI4MCIsInMiOiI1NDE1ODQ0ZjIyIiwiYyI6InRhbmtiIn0=/attachments/0",
"content-type": "application/pdf", "name": "WOORDZOEKER maken _ Online
_ Met oplossing2 copy.pdf", "size": 53398}, {"url": "https://se.api.mailgun.net/v3/domains/karaton.uk/messages/eyJwIjpmYWxzZSwiayI6IjEyNzQ1ZmViLTM4OTItNDdkZC04MTJiLWJlYzU4ZjNjYTI4MCIsInMiOiI1NDE1ODQ0ZjIyIiwiYyI6InRhbmtiIn0=/attachments/1",
"content-type":
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"name": "Geschatte uren.xlsx", "size": 44210}]', 'body-plain':
'\r\n\r\n', 'body-html': '\r\n', 'stripped-html':
'\n', 'stripped-text': '', 'stripped-signature': ''
}
Use the built-in JSON.parse() function, it'll return an array of objects as it should. It's opposed to JSON.stringify(), which does the opposite. So, basically,
JSON.parse(req.body.attachments) should do the trick.
JSON.parse should do the trick
const response = {
timestamp: '1538728432',
token: '0a1336769443d5a593d0ef7c1c817d29ef64ba422fc3cc45f1',
Subject: '2 attachments',
attachments: '[{"url": "https://se.api.mailgun.net/v3/domains/karaton.uk/messages/eyJwIjpmYWxzZSwiayI6IjEyNzQ1ZmViLTM4OTItNDdkZC04MTJiLWJlYzU4ZjNjYTI4MCIsInMiOiI1NDE1ODQ0ZjIyIiwiYyI6InRhbmtiIn0=/attachments/0", "content-type": "application/pdf", "name": "WOORDZOEKER maken _ Online _ Met oplossing2 copy.pdf", "size": 53398}, {"url": "https://se.api.mailgun.net/v3/domains/karaton.uk/messages/eyJwIjpmYWxzZSwiayI6IjEyNzQ1ZmViLTM4OTItNDdkZC04MTJiLWJlYzU4ZjNjYTI4MCIsInMiOiI1NDE1ODQ0ZjIyIiwiYyI6InRhbmtiIn0=/attachments/1", "content-type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "name": "Geschatte uren.xlsx", "size": 44210}]'
}
const attachments = JSON.parse(response.attachments);
console.log(attachments[0]);
console.log(attachments[1]);
Ref:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Categories