Getting data from MySql through express - mysql

I've set up a database on Heroku and I've created a table called users with 2 records, and now I'm trying to get the data into my Node application through express.
I've set up an connection like so in my app.js file:
// connect to the heroku database
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'us-cdbr-iron-***-**.cleardb.net',
user : 'bfe4***0ede74',
password : '6742****',
database : 'heroku_****ee0f0e9102'
});
I then have a routes folder with an index.js file:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
// res.render('layout', { title: 'Movieseat' });
connection.connect();
connection.query('SELECT * FROM `users` WHERE `first_name` = "Kees"', function (error, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
console.log(results);
});
connection.end();
});
module.exports = router;
In this index route I'm trying to serve the record of first_name Kees. But when I visit my host I get the following error:
connection is not defined
ReferenceError: connection is not defined
So it looks like connection has no reference in my route file, but in my WebStorm IDE when I ctrl + click on the connection I get my app.js file where I define my connection. So how do I reference connection in my route file?
Also when I uncomment the following line in my index.js route file:
res.render('layout', { title: 'Movieseat' });
I get the error:
Error: Can't set headers after they are sent. What would be the propper way to request data and render a jade template?

The second error is likely because somewhere you're calling res.send() or res.end() or res.render() already, you just don't realize it. Check your middleware and so on to make sure you're not doing so.
The first issue is because you're neither exporting the connection object from your connection file, nor requiring it in your router file. You always have to explicitly require a module in order to have reference to it.
// connect to the heroku database
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'us-cdbr-iron-***-**.cleardb.net',
user : 'bfe4***0ede74',
password : '6742****',
database : 'heroku_****ee0f0e9102'
});
module.exports = connection;
NOte that in that case, you will always have the same connection, which isn't great for scalability. Have a look at connection pooling and consider exporting a method that gets the connection rather than passing around a global object.
Then in your router:
var express = require('express');
var router = express.Router();
var connection = require('./path/to/your/connection.js');
/* GET home page. */
router.get('/', function(req, res, next) {
// res.render('layout', { title: 'Movieseat' });
connection.connect();
connection.query('SELECT * FROM `users` WHERE `first_name` = "Kees"', function (error, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
console.log(results);
});
connection.end();
});
module.exports = router;

Related

Unable to fetch data from workbench Mysql using node js

// import express js
const express = require('express')
// import a body-parser
const bodyparser = require('body-parser');
// executing the express js
const app = express();
// import mysql packages
const mysql = require('mysql');
// use bodyparser in express
app.use(bodyparser.json);
// create an connection details for mysql database
var mysqlConnection = mysql.createConnection(
{
host:'localhost',
user:'root',
password:'keerthi#abitech',
database:'employeedb'
}
)
// To connect with mysql database
mysqlConnection.connect((err)=>{
if(!err)
console.log('DB is connected')
else
console.log('DB connection is failed \n Error: ' + JSON.stringify(err, undefined, 2));
});
// establish an data fetch from database
app.get('/employees', (res, req)=>{
mysqlConnection.query('SELECT * FROM employee', (err, results)=>{
if(err) throw err;
console.log(results);
res.send("post is send")
})
});
// creating an server
app.listen(3000, ()=>console.log("server is running in port number 3000"));
This is my code. I am not able to fetch an data from mysql workbench.
The page is loading only does not give any response.
If i pass the link in postman it shows like this
Could Not Get Any Response
You are currently not sending your data back to the endpoint. Assuming that your connection is successful, you should res.send(results) instead of res.send("post is send") in order to send your results to the /employees endpoint.
Hope this fixes your problem.

How to display JSON file with Node.JS/Express

I'm VERY new to Node.js... so this is probably going to be stupid, basic. Here is what I am trying to do: I want to create a Node.js app that will query my MySQL database and return a JSON file to the user.
So far I have very little :) I have a project created with Webstorm. I have an index.js file and an index.ejs file. The index.js file has the following:
var express = require('express');
var router = express.Router();
var appdata = require('../data.json');
var mysql = require('mysql');
// http://nodejs.org/docs/v0.6.5/api/fs.html#fs.writeFile
var fs = require('fs');
var connection = mysql.createConnection({
host: 'xxxxxx',
user: 'xxxxx',
password: 'xxxxx'
database: 'xxxxx';
});
connection.connect();
router.get('/', function(request,response) {
connection.query('select AProgram_UID as UID, SiteDescription as Program, IcStatus as Status from AP_Details;', function (err, results, fields) {
if (err) {
console.log('Error in Query', err.message);
return response.send(500, err.message);
};
return JSON.stringify(results);
connection.end();
});
});
I haven't defined what goes in the index.ejs file because I really don't know where to go from here. I can write the JSON out to file from the code shown if I use writeFile, so I know the database part is correct.
Hopefully I explained enough... as mentioned, I'm new to Node. I just want to do something 'real' with it and this is something I need on a project I have.
Thanks!
In your router.get callback return the JSON back to the requester by using res.json to properly assign the Content-Type header to application/json and stringify whatever is passed to it.
Also you want to remove your return statements to before connection.end() otherwise connection.end() will never be called.
router.get('/', function(req, res) {
connection.query('select AProgram_UID as UID, SiteDescription as Program, IcStatus as Status from AP_Details;', function (err, results, fields) {
if (err) {
console.log('Error in Query', err.message);
res.status(500).send(err.message);
}
else
// render index view and pass in results JSON
res.json(results);
return connection.end()
});
});
Edit to use EJS View Engine Rendering
In order to use EJS you need to have your View Engine set to EJS and have a default Views directory setup. In your main Express server file it should look something like this before any routes
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
You'll need to change the code above from using res.json to use res.render. You'll also need to pass your results into the render function so the index.ejs can access the results JSON
res.render('index', { results: results });
In your index.ejs file you can access results using the EJS markup syntax
<html>
<body>
<p><% results %></p>
</body>
</html>

How to use express.js with mysql and express-myconnection?

I am using Express 4.9.0 and express-generator. Executed this command:
express --hbs projectname
Installed following modules with NPM:
mysql
express-myconnection
I want to make todo application. I have created separate file under routes/todo.js and created get/post routes for creating todos in that file using router.get and router.post.
i have following code in app.js:
// mysql connection
var connection = require('express-myconnection');
var mysql = require('mysql');
app.use(
connection(mysql, {
host : config.db.host,
user : config.db.user,
password : config.db.password,
database : config.db.database,
debug : false //set true if you wanna see debug logger
}, 'request')
);
// end of mysql connection
Where should i place mysql config and connection code? Inside todo.js? I still don't get concept of organisation file structure and where to place database queries.
I don't know if you eventually found the answer, but I thought it might help out others who accidentally stumbled on your question:
After you've setup like mentioned above, you can call the connection from the request object using the getConnection method like this:
exports.index = function(req, res) {
req.getConnection(function (err, connection) {
connection.query('select * from table_name', function(err, rows, fields){
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(rows);
}
});
});
};
This should print out a json with the content of your table all nice an pretty.
Hope this comes in handy.

How to properly use node-mysql?

I just started using node-mysql2 and I am confused how to use it properly. Examples:
(Implicitly established connection)
var express = require("express"),
app = express();
var mysql = require("mysql2");
var conn = mysql.createConnection({ ... });
app.VERB("/", function(req, res){
conn.query('SELECT 1+1 as test1', function(err, rows) {
// Show data to user...
// No .end() needed?
});
});
app.listen(8000);
second example:
var express = require("express"),
app = express();
var mysql = require("mysql2");
var conn = mysql.createConnection({ ... });
conn.connect(function(err){ ... }); // Is it right place to put it here? Or it has to go inside the callback below?
app.VERB("/", function(req, res){
conn.query("SELECT 1+1 as test1", function(err, rows){
// Show data to user...
conn.end(); // .end() necessary?
});
});
app.listen(8000);
Although I haven’t used node-mysql2, it is compatible with the original node-mysql module, so the same usage patterns apply.
The best way to use it is with connection pooling. That way, the MySQL client will create and destroy connections as needed. Your job is to call connection.release() when you no longer need a connection:
var express = require("express"),
app = express();
var mysql = require("mysql2");
var pool = mysql.createPool({ ... });
app.VERB("/", function(req, res){
pool.getConnection(function(err, conn) {
if (err) { /* handle the error and bail out */ }
conn.query('SELECT 1+1 as test1', function(err, rows) {
conn.release(); /* the connection is released back to the pool */
if (err) { /* handle the error */ }
else { /* show data to user */ }
});
});
});
app.listen(8000);
If your app runs “forever” (a web site for example) then you don’t need to call pool.end(). If you’re not using a connection pool, you don’t need to call connection.end() after each request. You wouldn’t want to: that would give you the overhead of establishing/tearing down the MySQL connection on every request!
If your app does not run “forever” (a command-line utility, for example), then call pool.end() or connection.end() just before you exit back to the command-line.

NodeJS sessions, cookies and mysql

I'm trying to build an auth system and I have app.js
var express = require('express')
, MemoryStore = require('express').session.MemoryStore
, app = express();
app.use(express.cookieParser());
app.use(express.session({ secret: 'keyboard cat', store: new MemoryStore({ reapInterval: 60000 * 10 })}));
app.use(app.router);
and the route.index as
var express = require('express')
, mysql = require('mysql')
, crypto = require('crypto')
, app = module.exports = express();
app.get('/*',function(req,res){
var url = req.url.split('/');
if (url[1] == 'favicon.ico')
return;
if (!req.session.user) {
if (url.length == 4 && url[1] == 'login') {
var connection = mysql.createConnection({
host : 'localhost',
user : 'user',
password : 'pass',
});
var result = null;
connection.connect();
connection.query('use database');
var word = url[3];
var password = crypto.createHash('md5').update(word).digest("hex");
connection.query('SELECT id,level FROM users WHERE email = "'+url[2]+'" AND password = "'+password+'"', function(err, rows, fields) {
if (err) throw err;
for (i in rows) {
result = rows[i].level;
}
req.session.user = result;
});
connection.end();
}
}
console.log(req.session.user)
when I access http://mydomain.com/login/user/pass a first time it shows in the last console call but a second time access the cookie is clean
Why do you not just use Express's session handling? if you use the express command line tool as express --sessions it will create the project template with session support. From there you can copy the session lines into your current project. There more information in How do sessions work in Express.js with Node.js? (which this looks like it may be a duplicate of)
As for sanitizing your SQL, you seem to be using the library, which will santitize your inputs for your if you use parameterized queries (ie, ? placeholders).
Final thing, you are using Express wrong (no offence). Express's router will let you split alot of your routes (along with allowing you to configure the favicon. See Unable to Change Favicon with Express.js (second answer).
Using the '/*' route will just catch all GET requests, which greatly limits what the router can do for you.
(continued from comments; putting it here for code blocks)
Now that you have an app with session support, try these two routes:
app.get('/makesession', function (req, res) {
req.session.message = 'Hello world';
res.end('Created session with message : Hello world');
});
app.get('/getsession', function (req, res) {
if (typeof req.session.message == 'undefined') {
res.end('No session');
} else {
res.end('Session message: '+req.session.message);
}
});
If you navigate in your browser to /makesession, it will set a session message and notify you that it did. Now if you navigate to /getsession, it will send you back the session message if it exists, or else it will tell you that the session does not exist.
You need to save your cookie value in the response object:
res.cookie('session', 'user', result);
http://expressjs.com/api.html#res.cookie