How to store parsed JSON value into a variable in Express? - javascript

I am using the body-parser to parse incoming JSON object in a POST message. I would like to store a particular value from the JSON into a variable to be sent to a database later.
Here is a snippet:
var http = require('http');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// Required to process the HTTP body.
// req.body has the Object while req.rawBody has the JSON string.
app.use(bodyParser.json()); // for parsing application/json
app.post('/', function(req, res){
var tropo = new TropoWebAPI();
parameters = req.body['session']['parameters'];
callerID = req.body['session']['from']['id'];
console.log(callerID);
if(callerID = 1234567)
{
\\Intentionally kept out
}
However, it fails with this TypeError: Cannot read property 'id' of undefined
#malix This is what the JSON object is:
"session": {
"id": "89c3b5d830dd8bb8b372f802aadbdfc9",
"accountId": "1234567",
"applicationId": "1234567",
"timestamp": "2016-06-23T17:09:48.685Z",
"userType": "HUMAN",
"initialText": null,
"callId": "7ab0b9306af2139a1a2e6cc8b7bd7af9",
"to": {
"id": "408XXXYYYY",
"name": "408XXXYYYY",
"channel": "VOICE",
"network": "SIP"
},
"from": {
"id": "408ZZZAAAA",
"name": "408ZZZAAAA",
"channel": "VOICE",
"network": "SIP"
},
}
I am trying to extract 408ZZZAAAA
Please assist.

I figured this out. Turns out the first POST message does give me the required result. The error only shows because my APP is configured to trigger a second POST from the source client. This second POST which triggers the same app.post(), does not have the "from" object all together. Therefore the error shows up on the second try, but I get what I need in the first post itself.

Related

body-parser is not parsing json data

This is how I am using the package:
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
This is the body of my request:
{
name: "jay",
price: "12"
}
This is how I am extracting the body:
const name = req.body.name;
const price = req.body.price;
But both name and price returned undefined.
EDITED:
According to VS Code, this package is deprecated. But it should still work, no?
the request body should be JSON so property names should be in quote signs
{
"name": "jay",
"price": "12"
}

Ignore Hyphen in Javascript (Postman)

Building a RestAPI with Postman.
I have some JSON data:
{
"progress-update": {
"#type": "parallel-progress",
"job": {
"#href": "/api/space/job-management/jobs/4691268"
},
"taskId": 4691268,
"jobName": "Compare Config-4691268",
"state": "DONE",
"status": "SUCCESS",
"percentage": 100,
"data": "<![CDATA[Total requests: 3<br>InSync count : 3<br>OutOfSync count : 0<br>]]>",
"subTask": [
{
I want to pull the "state" value into an environment Variable that i can then use to determine wether to continue on to the next request or wait until the state is DONE.
The problem i'm running into is "progress-update": has a hyphen in it, causing my script to not recognize it.
var jsonData = JSON.parse(responseBody);
pm.environment.set("JobStatus", jsonData.progress-update.state);
Postman returns the following error:
There was an error in evaluating the test script: ReferenceError:
update is not defined
You should be able to access your JSON data with
var jsonData = JSON.parse(responseBody);
pm.environment.set("JobStatus", jsonData['progress-update'].state);
using the object bracket notation

Consume AZURE ML with nodejs error 400 status code

I have a problem when I try to consuming the web service, the error is:
The request failed with status code: 400
{"error":
{"code":"BadArgument","message":"Invalid argument provided.",
"details":[{"code":"BatchJobInputsNotSpecified","message":"The following required input(s) were not specified with the request: input1. Please ensure all input data is specified and try again."}]}}
I don't know how to solve that, because in the code I send input1.
Please help me, thanks.
let req = require("request");
const uri = "bla";
const apiKey = "key";
let data = {
"Inputs": {
"input1":
[
{
'IdEmpleado': "20000",
'NivelSatisfaccion': "0.38",
'SatisfaccionLaboral_Disc': "Insatisfecho",
'UltimaEvaluacion': "0.53",
'UltimaEvaluacion_Disc': "Media",
'ProyectosRealizados': "2",
'ProyectosRealizados_Disc': "[2-3]",
'HorasMensuales': "157",
'HorasMensuales_Disc': "[150-199]",
'Antiguedad': "3",
'Antiguedad_Disc': "[2-4]",
'AccidentesTrabajo': "0",
'AccidentesTrabajo_Disc': "NO",
'Ascendido': "0",
'Ascendido_Disc': "NO",
'AreaTrabajo': "Ventas",
'NivelSalarial': "Bajo",
'Renuncia': "1",
'Renuncia_Disc': "SI"
}
],
},
"GlobalParameters": {}
}
The scoring uri expects the body of the request to be a JSON document with the following structure:
{
"data":
[
<model-specific-data-structure>
]
}
The structure of the data needs to match what the scoring script and model in the service expect. Please follow the following document for more information.

When post to express server after use JSON.stringify, it doesn't work

I am trying to send a simple array to express server as JSON, then convert it back to an object on the server side.
Client side :
var hand = { cards: [] }
// I randomly generate some numbers and suits and then add to the array.
var card_obj = { "number": number, "suit": suit };
hand.cards.push(card_obj)
//Send to Express server
var hand_json = JSON.stringify(hand)
$.post("hand", hand_json, function(result) {
console.log(result);
});
Server side :
app.post("/hand", function(req, res) {
var cards = req.body.cards
console.log(cards[0])
});
This code is not working,as I receive on the server side console : Cannot read property '0' of undefined
BUT, it will work, If i changed the client code to the following :
var test = { "cards": [{ "number": "9", "suit": "club" }, { "number": "10", "suit": "club" }, { "number": "K", "suit": "spades" }, { "number": "A", "suit": "hearts" }, { "number": "5", "suit": "diamonds" }] }
$.post("hand", test , function(result) {
console.log(result);
});
The weird thing that the test variable is the same variable generated by JSON.stringify(hand), I just copied it form the console.
I don't understand why when use JSON.stringify(hand), it doesn't work. But when copy paste the object and then pass it, it works.
In order to send a post request content JSON in the body you need to make sure two things:
Since you are using JQuery. From client, you must use ajax function to include a contentType:"application/json in your request to inform the server you are sending a JSON file:
$.ajax({
url: url,
type:"POST",
data: JSON.stringify(hand),
contentType:"application/json",
dataType:"json",
success: function(result){
`...Do something when the data returned`
}
})
Now in the server, you should install and define a middleware to work as body parser for your post requests
Install npm install body-parser --save
And use it in express
const bodyParser = require('body-parser');
// support parsing of application/json type post data
app.use(bodyParser.json());
//And make sure your route is placed below the parser
app.post("/hand", function(req, res) {
var cards = req.body.cards
console.log(cards[0])
});

How can I post a container in Storage api from loopback?

I already have declared my datasource ,my model and the connector between these.
My model
{
"name": "container",
"base": "Model",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
Datasource
"storage": {
"name": "storage",
"connector": "loopback-component-storage",
"provider": "filesystem",
"root": "./server/storage"
}
My provider
{
"filesystem": {
"root": "./server/storage"
}
}
And the Connector
"container": {
"dataSource": "storage",
"public": true
}
I try posting a object like {"Object":"container1"} into path "./server/storage" but I get the following error from callback.
{
"error": {
"statusCode": 500,
"name": "TypeError",
"message": "Path must be a string. Received undefined",
"stack": "TypeError: Path must be a string. Received undefined.."
}
}
Please who can help me to find my issue? Thanks!
You can also use "name" instead of "Object" as key in your JSON object to create a new container/directory using the API.
POST /api/containers {"name":"container1"}
The way to post a container is, without using the loopback api. Create a folder that is gonna be the container into your provider path (being filesystem).
As simple as that!
If you need a programmatic way to add new containers, let's say for example you want to create a filesystem of sorts for new users. You can use the route below. "Container" is the name I called my Model, you can call yours whatever you'd like.
POST localhost:3000/api/container
Inside the body of the post request you have to have an attribute name and the value of the name can be the new container you're creating. The Strongloop/Loopback documentation, which can be found here, is not accurate and neither is the error you get back when you try to post it with their directions.
"error": {
"statusCode": 500,
"name": "TypeError",
"message": "Path must be a string. Received undefined"
}
An excerpt of the code to send a post request to create a new container is also below.
var request = require("request");
var options = {
method: 'POST',
url: 'http://localhost:3000/api/containers',
body: { name: 'someNewContainer' },
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});

Categories