Send MySql result in res.send - mysql

I'm kind of newbie to the node.js, this might be silly one but not actually getting proper way to achieve this. here I'm trying to send the mysql result from the node.js res.send() method, here below I'm adding my code.
router.post('/get_doc_msgs', (req, res)=>{
var d_msg = "SELECT * FROM msgs WHERE d_id = ?";
var d_msgs = [req.body.doc_id_msgs];
db.query(d_msg, d_msgs, (err,rows) => {
if(err){
console.log('error ', err);
}
else{
res.send(rows)
}
});
})
and here is my function to get the data to the rendered ejs file.
function getmsgs(){
$.ajax({
type:'POST',
url: '/get_doc_msgs',
data: {
doc_id_msgs : $('#doct_id').val();
},
success: function(data){
$('#msg_q').html(data);
}
})
}
advance thank you for help and suggestions .

Here's a complete example of how this might work, I've added server and client code.
If you run
node app.js
Then go to http://localhost:3000 you should see the example working.
The main issue I believe is you need to use a body-parser in Express so you can parse uploaded data correctly. In this case I've used JSON, you could use another encoding if you wished.
The only change I made to the server code was really to add the body parser.
On the client side, I set a content-type header and used JSON.stringify() on the uploaded data.
It's not a silly question, getting all this stuff to play nice takes a little bit of practice and effort!
app.js
const mysql = require('mysql');
const express = require('express');
const app = express();
const router = app;
const port = 3000;
const bodyParser = require("body-parser");
// Add the credentials to access your database
var db = mysql.createConnection({
host : 'localhost',
user : '<user>', /* replace these with real values. */
password : '<pw>', /* replace these with real values. */
database : '<db>' /* replace these with real values. */
});
app.use(bodyParser.json());
app.use(express.static("./"));
router.post('/get_doc_msgs', (req, res)=>{
var d_msg = "SELECT * FROM msgs WHERE d_id = ?";
var d_msgs = [req.body.doc_id_msgs];
db.query(d_msg, d_msgs, (err,rows) => {
if(err){
console.log('error ', err);
} else {
res.send(rows)
}
});
})
app.listen(port);
index.html
<!DOCTYPE html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
</head>
<body style="padding:20px">
<label>Doc id:</label><input id="doct_id" value="1"/>
<h4>Response:</h4>
<p id="msg_q"></p>
<script>
function getmsgs() {
$.ajax({
type: 'POST',
url: '/get_doc_msgs',
contentType: "application/json",
data: JSON.stringify({
doc_id_msgs : $('#doct_id').val()
}),
dataType: "json",
success: function(data) {
for(row of data) {
$('#msg_q').append("<li>" + Object.values(row).join("\t") + "</li>");
}
}
})
}
console.log("Doc id:", $('#doct_id').val());
getmsgs();
</script>
</body>
</html>

`getDocMessg = (req, res, next) => {
mess_id = req.body.doc_id_msgs
db.execute("SELECT* FROM msgs WHERE d_id = ?", [mess_id]).then((results) => {
res to render the page you want to send the data to
res.render('name of page', {
message : results[0]
})
})
}`
something like that should do the job you need to adapt it to your website structure, using ejs you can call the variable message and show it on your page :)

Related

I am trying to display a html file using res.sendFile in express

i am trying to implement a work flow, where, when the user logs in, the user credentials is posted to one of the routes in express via ajax to check if the user exists, if the user exists, the express route will send back a message "authorised" to the ajax call, and the success callback is invoked where another ajax call sends a header along with data to the express route(/reroute). This express /reroute api is trying to res.redirect to another route /homepage. Inside the /homepage route i am attempting to display a html file using res.sendfile, and the res.sendfile is not working.
my login ajax call
$(document).on("click", "#login", (e) => {
const email = $('#logemail').val().trim();
const pass = $('#password').val().trim();
$.ajax({
url: "http://localhost:4000/checkuserexists",
type: "POST",
dataType: "JSON",
data: {
email: email,
pass: pass
},
success: function(data, textStatus, request) {
console.log(data)
if (data.message === "authorised") {
const token = request.getResponseHeader('access-token');
localStorage.setItem("access-token", token);
$.ajax({
url: "http://localhost:4000/reroute",
type: "GET",
dataType: "JSON",
beforeSend: function(xhr) {
xhr.setRequestHeader('access-token', token);
},
data: {
redirectTo: 'homepage'
},
success: function(data) {
console.log(data + " from ajax ")
}
})
} else {
$('.alertbox').show();
$('.alertbox').text("User unauthorised");
}
}
})
})
my express route (/reroute)
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
if (req.header('access-token')) {
const token = req.header('access-token');
const redirectTo = req.query.redirectTo;
if (redirectTo === 'homepage') {
res.setHeader('access-token', token)
res.redirect('/homepage')
}
}
})
module.exports = router;
my homepage route
const express = require('express');
const path = require('path');
const token_middleware = require('../middlewares/jwtauth');
const router = express.Router();
router.use(express.static(path.join(__dirname, "../public")))
router.get('/', token_middleware, (req, res) => {
if (req.status === "exists") {
res.sendFile(path.join(__dirname, "../public/homepage.html"));
} else {
res.redirect('/');
}
})
module.exports = router;
You're requesting the URL with Ajax.
The browser asks for /reroute and gets a redirect to /homepage.
It then asks for /homepage and gets an HTML document.
It passes that HTML document to the JavaScript engine and jQuery tries to parse it as JSON (it ignores the Content-Type because you said dataType: "JSON") and errors.
If you want to do this with Ajax, then don't redirect. Return some JSON that tells your code the login was successful. Then you can navigate with client-side JS and the location object.
If you want to redirect, then use a regular form submission and not Ajax.

how to make a post request inside async function?

At the end of the waterfall-dialog in "summary" (i.e., the last if statement) i want to automatically make a post request without making an API call in Postman, is eventListener the way? How to include it?
async summaryStep(step) {
if (step.result) {
// Get the current profile object from user state.
const userProfile = await this.userProfile.get(step.context, new UserProfile());
userProfile.name = step.values.name;
//the same for other step values(email, doctor, date)
let msg = `you want a date with dr. ${userProfile.doctor} , and your name is ${userProfile.name}.`;
if (userProfile.date !== -1) {
msg += `you have an appointment the: ${userProfile.date}.`;
}
await step.context.sendActivity(msg);
let msg1 = `"${userProfile.date}"`;
if (msg1) {
let z = JSON.stringify(userProfile.name);
//and also the other rows to go in the database(email, doctor, date)
var name = JSON.parse(z);
//and also the other rows to go in the database(email, doctor, date)
//this actually works but only if i use postman
var urlencoded = bodyparser.urlencoded({ extended: false });
app.post('/id', urlencoded, (req, res) => {
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
mysqlConnection.query("INSERT INTO users(name, email, doctor, date) VALUES('" + userProfile.name + "','" + userProfile.password + "','" + userProfile.doctor + "','" + userProfile.date + "')", function (err, result, rows) {
if (err) throw err;
console.log("Yeah! record inserted");
console.log(name);
res.send(result);
});
});
const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Listening on port ${port}..`));
}
} else {
await step.context.sendActivity('Thanks. Your profile will not be kept. Push enter to return Menu');
}
return await step.prompt(CONFIRM_PROMPT3, `is that true? ${step.result}`, ['yes', 'no']);
// this if statement should "fire" the post request...
if (step.result == 'yes') {
return await step.context.sendActivity(`we will contact you soon ${userProfile.password}.`);
}
return await step.endDialog();
}
Per my understanding , you want to know how to call an POST API from Azure bot async function. Pls try the code below in your async summaryStep function to send the post request based on your requirement.
var rp = require('request-promise');
var options = {
method: 'POST',
uri: 'http://localhost:8080/id',
body: {
fieldCount:0,
affectedRows:1,
//your other body content here...
},
json: true,
headers: {
'content-type': 'application/json' //you can append other headers here
}
};
await rp(options)
.then(function (body) {
console.log(body)
})
.catch(function (err) {
console.log(err)
});
}
Hope it helps .
A
nd if there is any further concerns or misunderstand , pls feel free to let me know.
The answer is to move your app.post API endpoint to your index.js file where your bot is already running on a server. Simply spin up a new "server" and "port" making the endpoint available. Then, in your summaryStep (axiosStep in my example), make your API call using Axios, request-promise, or what have you, to post your data. When the API is hit, the data will be passed in and processed.
In the code below, when the API is hit the passed in data is used in a sendActivity posted back to the bot. In your case, your passed in data would be used for the database call in which you could use the returned response in the sendActivity.
Your code would look something like the following. Please note, the post actions are simplified for the sake of the example. You would need to update the post actions to make your mySql queries. This sample also makes use of restify for the server (standard for Bot Framework bots) and uses the same port as the bot, but this can easily be updated to use Express and/or another port.
Hope of help!
index.js
[...]
const conversationReferences = {};
const bodyParser = require('body-parser');
server.post('/id', async (req, res) => {
const { conversationID, data, name } = req.body;
const conversationReference = conversationReferences[ conversationID ];
await adapter.continueConversation(conversationReference, async turnContext => {
var reply = `${ data }. Thanks, ${ name }`;
await turnContext.sendActivity(reply);
});
res.writeHead(200);
res.end();
});
mainDialog.js
async axiosStep ( stepContext ) {
const conversationID = stepContext.context.activity.conversation.id;
try {
const response = await axios.post(`http://localhost:3978/id`, {
data: "Yeah! Record inserted",
name: "Steve",
conversationID: conversationID
})
console.log(response);
} catch (error) {
console.log(error);
}
return stepContext.next();
}

Display data in html/js file using NodeJs from mysql database

My index.js file is
var express = require('express');
var app = express();
var path = require('path');
var router = express.Router();
var data = require('./data/jsonData');
var createDatabase = require('./data/db');
var careateTable = require('./data/createTable');
var insert = require('./data/insert');
var bodyParser = require('body-parser');
var select = require('./data/select');
app.use(express.static(path.join(__dirname, 'www')));
app.use(express.static(path.join(__dirname, 'form')));
app.use(bodyParser());
app.get('/' , function (req , res) {
res.sendFile(path.join(__dirname + '/www/index.html'));
});
app.get('/data' ,function (req , res) {
res.json(data);
});
app.get('/form' ,function (req , res) {
res.sendFile(path.join(__dirname + '/form/index.html'));
});
app.post('/form' ,function (req , res) {
console.log(req.body.user);
console.log(req.body.password);
insert.insertModule(req.body.user , req.body.password);
res.sendFile(path.join(__dirname + '/www/index.html'));
});
app.get('/show' , function (req , res) {
var i ;
select.select( function (err, results) {
if (err == 'error') {
console.log(err);
} else {
console.log(results);
res.send(results.username);
}
});
});
app.listen(3000);
console.log("App is listning on port 3000");
and select.js is
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "NodeDataBase"
});
con.connect(function (err) {
if (err) throw err;
console.log("Connected!");
});
module.exports = {
select: function (callback) {
var sql = "SELECT username , password FROM login ";
con.query(sql, function (err, result , fields) {
if (err) {
callback("error", err)
} else {
callback("success", result)
}
});
}
}
I want to show the results object data to html file , So how can i do this please suggest me.
from a get request /show it will show all userdata fetched from the database
I´ll try to explain the way it works (with the consideration on you are now able to see the data on 'http://localhost:3000/show') . Plz, guys, correct me if I do explain something in the wrong way.
There, what you have in your code, is the
Server side code
mysql: Declares connection to database (this is your database connector)
node.js: Declares methods to put/push/get data from database (your server side as is)
express.js: Declares urls to put/push/get data from database (http/https router)
Then, if we check the code, we can see the declaration of a server api - for example app.get('/show')
There, what you are saying is that express, will use the url /show with the method GET
Here is where your client appears in scene. Now, we suppose your server is up and running, waiting to serve GET petitions on http://localhost:3000/show.
If that is correct, when clicking the link you should see the user names, and now you will need an http client to connect to your http server side.
The way you can grab data on your HTML client from your server, is javascript.
Then, you will need to build an HTML file, that will also contain a javascript script (in my example written in angular).
The HTML (this is written in jade. you can convert it) should look like this:
Client HTML Code
You should create an index.html file, and paste this code
<!doctype html>
<html ng-app>
<head>
<title>My AngularJS App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body>
<div ng-controller="MyCtrl">
<table>
<thead>
<tr>
<th>
<p>Name</p>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users">
<td>
<p>{{user}}</p>
</td>
</tr>
</tbody>
</table>
</div>
<script>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope, $http) {
//This method will call your server, with the GET method and the url /show
$http.get("http://localhost:3000/show").then(function(success){
if(success.data.length>0)
{
$scope.users=success.data;
}
});
}
</script>
</body>
</html>
This code should capture the data and show a row in the table for every name in the database.
Hope it helps, at least as a clear explanation of how the full stack (client-server) works.
May be you can use view engine such As EJS, Jade to render data from node to the front end.
If you want to render the data on the html page, i will do it like http://localhost:3000/show : with json -resonponse
var express = require('express');
var app = express();
require('json-response');
app.get('/', function(req, res){
res.ok({foo: 'bar'}, 'hello world');
});
i will return json from the link and in Index.html with the help of jquery/Ajax will hit the link , retrieve the value and show it on HTML

How to receive (and decode) JSON from post data in Node.Js Express?

Suppose I have sent data with the following code:
$.ajax({
type: "POST",
url: "/save/" + #{key},
data: transitions2,
success: function (data) {
},
dataType: "json"
});
where transitions2 is hierarchical JS object.
Now how can I receive it intact at server side
router.post('/save/:key', function(req, res) {
// where is my data here?
});
UPDATE
I found info about body parsers, and found that my site template already contained them. Particularly, app.js contains:
...
var bodyParser = require('body-parser');
...
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/data', express.static(path.join(__dirname, '../data')));
app.use('/', index);
...
So I wrote in my index.js:
...
router.post('/save/:key', function(req, res) {
var transitions = req.body;
image_data.save_transitions(req.params.key, req.query.postfix, transitions);
});
...
Unfortunately, transitions contains
while on client side it contained
i.e. was full of data.
What can be the problem?
UPDATE 2
I tried to do
$.ajax({
type: "POST",
url: "/save/" + #{key},
data: JSON.stringify(transitions2),
success: function (data) {
}
});
and I see in Fiddler2 now, that full Json is passed.
[{"start_image":"20170402_1_NATURAL_COL0R","end_image":"20170409_1_NATURAL_COL0R","transition_classes":["no_transition","some_activity"]},...
Unfortunately, on server side I observe truncated and corrupted string
(equal sign should not be in JSON).
And JSON.parse fails.
use body-parser middleware to retrieve the data.
npm install body-parser
configure this in express app.
Find below the sample code
var bodyParser = require('body-parser');
app.use(bodyParser.json());
Then in your router use the following:
router.post('/save/:key', function(req, res) {
var data = req.body // here is your data
});
The problem was on client side only. Correc way to post complex object with json is:
$.ajax({
type: "POST",
url: "/save/" + #{key},
data: JSON.stringify(transitions2),
contentType: "application/json; charset=utf-8",
success: function (data) {
}
});
stringify and contentType are obligatory.
front:
axios.post('/attack', {
number:number,
count:count
},
{
headers:{contentType: "application/json; charset=utf-8"}
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
}
back:
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.json())
app.post('/attack', (req, res) => {
let data = req.body
console.log(data)
res.send('200')
})
console log: { number: '(number)', count: '(count)' }

nodeJS - make HTTPS request, sending JSON data

I would like to send an HTTPS POST from one nodeJS server to another. I have some JSON data I would like to send with this request (populated by a html form).
How can I do this? I am aware of https.request() but there does not seem to be an option to include JSON as a part of the query. From my research it seems possible with an HTTP request, but not an HTTPS request. How can I solve this?
const pug = require('pug');
var cloudinary = require('cloudinary');
var express = require('express');
var multer = require('multer');
var upload = multer({ dest: 'uploads/' });
var request = require('request');
var bodyParser = require('body-parser');
var options = {
hostname: 'ec2-54-202-139-197.us-west-2.compute.amazonaws.com',
port: 443,
path: '/',
method: 'GET'
};
var app = express();
var parser = bodyParser.raw();
app.use(parser);
app.set('view engine', 'pug');
app.get('/', upload.single('avatar'), function(req, res) {
return res.render('index.pug');
});
app.get('/makeRequest*', function(req, res) {
query = req['query'];
/*
Here, I would like to send the contents of the query variable as JSON to the server specified in options.
*/
});
You can send JSON data through a POST http request with the native https node module, as stated in the documentation
All options from http.request() are valid.
So, taking the http.request() example you can do the following:
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
var req = https.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();
You should edit postData to your desired JSON object
I believe the below is what you want. Using the request library. See comments in the code for my recommendations.
...
var options = {
hostname: 'ec2-54-202-139-197.us-west-2.compute.amazonaws.com',
port: 443,
path: '/',
method: 'POST',
json: true
};
...
//making a post request and sending up your query is better then putting it in the query string
app.post('/makeRequest', function(req, res) {
var query = req.body['query'];
//NOTE, you cannot use a GET request to send JSON. You'll need to use a POST request.
//(you may need to make changes on your other servers)
options.body = { payload: query };
request(options, function(err, response, body) {
if (err) {
//Handle error
return;
}
if (response.statusCode == 200) {
console.log('contents received');
}
});
});
as matt mentioned you need to use request
to send JSON object not JSON.Stringify so that at the server you can receive it using:
app.post('/makeRequest', function(req, res) {
console.log (req.body.param1);
}
Use the following code:
var request = require("request");
request({
'url':"http://www.url.com",
method: "POST",
json: true,
body: {'param1':'any value'}
}, function (error, resp, body) {
console.log ("check response.");
});