Node.js service for put operation - json

Hello I want to put operation in a JSON format . Probably My JSON parse error so that I can't able to update Data . My JSON body data is
[{
"receiptNo": "21456",
"rollno": 12201,
"bankcode": 2,
"userid": "rifat",
"__v": "0"
}]
And my NodeJS code :
router.put('/receiptmaster1/update/:receiptNo', function (req,res) {
receipt_master1.updateMany({
receiptNo: req.params.receiptNo
}, {
receiptNo: req.body.receiptNo,
rollno: req.body.rollno,
bankcode : req.body.bankcode,
userid: 'rifat',
__v: "0"
}).then(function(err) {
res.send({
success: true,
message: "Updated Successfully Master2"
});
}).catch(err => {
res.status(500).send({
message: err.message || "Error while Updating Server Data"
});
});
});
My data is not updated though I have got this response
"success":true,"message":"Updated Successfully Master2"
Please Help.

Your JSON is a single object in an array. Either change the posted format to be an object (without the wrapping array) when you send it:
{
"receiptNo": "21456",
"rollno": 12201,
"bankcode": 2,
"userid": "rifat",
"__v": "0"
}
or change how you access it on the server:
router.put('/receiptmaster1/update/:receiptNo', function (req,res) {
receipt_master1.updateMany({
receiptNo: req.params.receiptNo
}, {
receiptNo: req.body[0].receiptNo,
rollno: req.body[0].rollno,
bankcode : req.body[0].bankcode,
userid: 'rifat',
__v: "0"
}).then(function(err) {
res.send({
success: true,
message: "Updated Successfully Master2"
});
}).catch(err => {
res.status(500).send({
message: err.message || "Error while Updating Server Data"
});
});
});
Note the change from req.body. to req.body[0].

Related

directline connection role and name not getting in BOT conversationUpdate

//For reference below - DirectLine Connection code
```(async function() {
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({
secret: “My KEY”}),
userID : "myid",
username: "myName"
},
document.getElementById('chat_converse')
);
document.querySelector('#chat_converse > *').focus();
})().catch(err => console.error(err));```
//Once Connected. We will have below objects in BOT.
```{
"type": "conversationUpdate",
"id": "ERqgImAulq3",
"timestamp": "2020-06-18T07:07:03.448Z",
"serviceUrl": "https://directline.botframework.com/",
"channelId": "directline",
"from": {
"id": "AicCk0YN2Ap9n2Ev1ovbuc-k"
},
"conversation": {
"id": "AicCk0YN2Ap9n2Ev1ovbuc-k"
},
"recipient": {
"id": "BotName#xp113vQdWDM",
"name": "BotName"
},
"membersAdded": [
{
"id": "BotName#xp113vQdWDM",
"name": "BotName"
}
]
}```
//From - section we should get id, name, role. In the "from" object name and role key is missing //and id is present but with auto generated id not actual user id myid.
You're not getting a ConversationUpdate for the user, just the bot. You need to send a ConversationUpdate manually:
const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'webchat/join',
value: { language: window.navigator.language }
}
});
}
return next(action);
});
I have applied as below in my code, It helps. May be useful for others
const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'webchat/join',
value: { language: window.navigator.language }
}
});
}
return next(action);
});
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({
secret: 'YourKey'
}),
userID : "UserID",
username: "UserName",
store
},
document.getElementById('chat_converse')
);
document.querySelector('#chat_converse > *').focus();
})().catch(err => console.error(err));
It will trigger two time bot activity, One without user info, One with user info. So I did checked at bot side if user info contains name kay then load my initial dialog something like below..It got worked for me. Thanks #mdrichardson
if (membersAdded[cnt].id === context.activity.recipient.id && context.activity.from && context.activity.from.name
&& context.activity.channelId=='directline') {
await dialog.run(context, conversationState.createProperty('DialogState'));
}

ReactJS - How to deserialize and show a serialized JSON response?

I'm getting a serialized JSON body from our API like the below example: '
{
"_embedded": [
{
"id": 1,
"vulnerable": false,
"systemId": "something",
"friendlyName": "a friendly name"
},
]
}
How to show just the key/value friendlyName? I'm using axios to get the response. This is my code:
axios.get(BASE_URL + 'household/list',{
headers: { Authorization: AuthStr },
transformResponse: axios.defaults.transformResponse.concat((data) => {
console.log(data) // this should now be JSON
})
}).then(({ data })=> {
this.setState({
data: houses.friendlyName
});
})
.catch((err)=> {
console.log(err);
});
I think I'm supposed to transform the data, but I don't know how. Thanks for any help.
Edit: This is how the response is shown in console:
_embedded:
0:
friendlyName: "a friendly name"
id: 1
systemId: "GE8BP2IACH7"
vulnerable: false
So, how do I deserialize it?
axios.get(BASE_URL + 'household/list',{
headers: { Authorization: AuthStr },
}).then(function (response) {
this.setState({data:response._embedded.friendlyName})
})
.catch(function (error) {
console.log(error);
});

How to get results from MySql DB using node.js MySQL and send them back to API.ai - DialogFlow

I am having issues retrieving and sending results from a MySql database to API.ai. The concrete question is how to wait for the results to be available, and then send the results in the Json object back to API.ai
This is what I have:
In the webhook or service, after receiving the Json request, I call a method:
if (action === 'get.data') {
// Call the callDBJokes method
callDB().then((output) => {
// Return the results to API.AI
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(output));
}).catch((error) => {
// If there is an error let the user know
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(error));
});
}
which calls the method callDB() where the database call is executed:
function callDB() {
return new Promise((resolve, reject) => {
try {
var connection = mysql.createConnection({
host: "127.0.0.1",
user: "root",
password: "x",
database: 'y'
});
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (!error) {
let response = "The solution is: " + results[0].solution;
response = response.toString();
let output = {'speech': response, 'displayText': response};
console.log(output);
resolve(output);
} else {
let output = {'speech': 'Error. Query Failed.', 'displayText': 'Error. Query Failed.'};
console.log(output);
reject(output);
}
});
connection.end();
} catch (err) {
let output = {'speech': 'try-cacth block error', 'displayText': 'try-cacth block error'};
console.log(output);
reject(output);
}
}
);
}
I get a Json response in API.ai like:
{
"id": "5daf182b-009f-4c11-a654-f2c65caa415e",
"timestamp": "2017-08-29T07:24:39.709Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "get data",
"action": "get.data",
"actionIncomplete": false,
"parameters": {},
"contexts": [
{
"name": "location",
"parameters": {
"date": "",
"geo-city": "Perth",
"date.original": "",
"geo-city.original": "perth"
},
"lifespan": 2
},
{
"name": "smalltalkagentgeneral-followup",
"parameters": {},
"lifespan": 2
}
],
"metadata": {
"intentId": "4043ad70-289f-441c-9381-e82fdd9a9985",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false",
"webhookResponseTime": 387,
"intentName": "smalltalk.agent.general"
},
**"fulfillment": {
"speech": "error",
"displayText": "error",
"messages": [
{
"type": 0,
"speech": "error"**
}
]
},
"score": 1
},
**"status": {
"code": 200,
"errorType": "success"**
},
"sessionId": "c326c828-aa47-490c-9ca0-37827a4e348a"
}
I am getting only the error message but not the result from the database. I read that it could be done using callbacks as well, but I could not figure it out yet. I can see that the database connection is working, because the logs of the connections shows the connection attempts.
Any help will be appreciated. Thanks.
Solved by declaring the var mysql = require('mysql'); as const mysql = require('mysql'); not inside the function, but before the exports.myfunction declaration. Working example code to get results from MySql DB using node.js MySQL, and send them back to API.ai is as follows:
'use strict';
const mysql = require('mysql');
exports.her_goes_your_function_name = (req, res) => { //add your function name
//Determine the required action
let action = req.body.result['action'];
if (action === 'get.data') {
// Call the callDBJokes method
callDB().then((output) => {
// Return the results of the weather API to API.AI
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(output));
}).catch((error) => {
// If there is an error let the user know
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(error));
});
}
};
function callDB() {
return new Promise((resolve, reject) => {
try {
var connection = mysql.createConnection({
host: "127.0.0.1",
user: "your_user",
password: "your_pass",
database: "your_DB"
});
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (!error) {
let response = "The solution is: " + results[0].solution;
response = response.toString();
let output = {'speech': response, 'displayText': response};
console.log(output);
resolve(output);
} else {
let output = {'speech': 'Error. Query Failed.', 'displayText': 'Error. Query Failed.'};
console.log(output);
reject(output);
}
});
connection.end();
} catch (err) {
let output = {'speech': 'try-cacth block error', 'displayText': 'try-cacth block error'};
console.log(output);
reject(output);
}
}
);
}

Angular get to JSON file displaying as empty

I am new to angular and trying to integrate it within my application. I am attempting to use a simple $http.get to a .JSON file, which seems to be found, but when trying to pass the data to the front end, or even alert it, is it alerting as []
Here my get:
$scope.countries = [];
$http.get('/resources/data/countries-report.json', function(data){
$scope.countries = data;
}, function(error) {
//handle error here
});
alert(JSON.stringify($scope.countries));
Here's my .JSON file:
{
"firstName" : "Joe",
"surName" : "Bloggs",
"countries" : [
{ "name": "France", "population": "63.1" },
{ "name": "Span", "population": "52.3" },
{ "name": "United Kingdom", "population": "61.8" }
]
}
Try this:
$scope.countries = [];
$http.get('/resources/data/countries-report.json', function(data){
$scope.countries = data;
alert(JSON.stringify($scope.countries));
}, function(error) {
//handle error here
});
Alert should go in the callback.
This should do it
$http.get('/resources/data/countries-report.json').success(function(data) {
$scope.countries = data;
alert(JSON.stringify($scope.countries));
}).error(function(error) {
alert('error');
});
also this equivalent would work
$http.get('/resources/data/countries-report.json').then(function(data) {
$scope.countries = data;
alert(JSON.stringify($scope.countries));
}, function(error) {
alert('error');
});
Edit --
Instead of $http.get('/someUrl', sucessCallback, errorCallback) it should be either
$http.get('/someUrl').success(successCallback).error(errorCallback)
or
$http.get('/someUrl').then(successCallback, errorCallback)
see docs
Because $http.get is asynchronous alert should be moved in the successCallback function, to ensure that $scope.countries=data is executed before calling alert.
$http.get is an async function. when you try alert(JSON.stringify($scope.countries)); $scope.countries is equals to []. You must wait for server response before using data.
Try to do your alert into success function
$scope.countries = [];
$http.get('/resources/data/countries-report.json', function(data){
$scope.countries = data;
alert(JSON.stringify($scope.countries));
}, function(error) {
//handle error here
});

Passport authenticate and JSON response

I'm building a webapplication in NodeJS.
Back-end in application is connected with user just via Json API. I'm trying to do login option. It's possible? How can I receive response from Passport Authenticate?
function post_api(req, res) {
res.writeHead(200, { 'Content-Type': 'application/json' });
// Check method
if(!req.body.method)
res.write( JSON.stringify({
"status":"400",
"response": {
"status" : "error",
"info": "Method not defined."
}
}));
else
{
if(req.body.method == "login")
{
passport.authenticate('local', {failureFlash: true, successFlash: true});
// Something here but i have no idea what...
res.write( JSON.stringify({
"status":"200",
"response": {
"status" : "error", // or success
"info": req.flash('error')
}
}));
}
else
res.write( JSON.stringify({
"status":"404",
"response": {
"status" : "error",
"info": "Method not found."
}
}));
}
res.end(); };
This of course doesn't works, how it should look like?