I am passing data to my back-end server. I am using JavaScript and Node.JS with the Express library. I am running the backend on port 80 and the frontend on 8080. I am trying to pass data which I can do for strings with no problem, but when I try and pass integers (or dates), I get undefined. The relevant front end code is:
var params = '{ \"clientUIC\": \"'+myClientUIC+'\", \"clientName\": \"'+myClientName+'\", \"clientGroup\": \"' + myClientGroup+ '\", \"clientNACE\": \"' + myNACE +'\", \"creditLine\": \"' + myCreditLine + '\", \"creditLineDate\": \"' + myCreditLineDate + '\", \"clientCurrency\": \"' + myCurrency + '\", \"clientCity\": \"' + myClientCity + '\", \"clientCountry\": \"' + myClientCountry + '\"}';
console.log("params " + params);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:80/deploy_client", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(params);
An example of the formed JSON is:
params { "clientUIC": "ABC123", "clientName": "Client 180", "clientGroup": "Group 5", "clientNACE": "J", "creditLine": "85000000000", "creditLineDate": "1579651200", "clientCurrency": "EUR", "clientCity": "Den Haag", "clientCountry": "NLD"}
When I read it in the node.js backend, it is fine for strings but not for the numbers. I am reading req.body as follows:
app.post('/deploy_client', (req, res) => {
var myClientUIC = req.body.clientUIC;
myClientUIC = convertStringX(myClientUIC, 16);
console.log("myClientUIC "+ myClientUIC);
...
var myCreditLine = req.body.clientCreditLine;
console.log("myCreditLine "+ myCreditLine);
var myCreditLineDate = req.body.clientCreditLineDate;
console.log("myCreditLineDate "+ myCreditLineDate);
...
For the strings, req.body. works perfectly but for credit line and credit line date console.log returns undefined.
How do I properly deparse the JSON in node.js?
The params you are looking for are missing in your body request
In my opinion you should stringify an object instead of concatenating a string for your request body, it would be easier to read.
var params = {
clientUIC: myClientUIC,
clientName: myClientName,
clientGroup: myClientGroup,
clientNACE: myNACE,
// There is no clientCreditLine
creditLine: myCreditLine,
// There is no clientCreaditLineDate
creditLineDate: myCreditLineDate,
clientCurrency: myCurrency,
clientCity: myClientCity,
clientCountry: myClientCountry
}';
console.log(params);
const strParams = JSON.stringify(params);
console.log(strParams);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:80/deploy_client", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(strParams);