Data shows on server response, but not on browser - MySQL Node.js - mysql

When I run http://localhost:1337 I get this as my output Hello, [object Object] but on the server response, the output is Hello, David James. It works on the server response but not on the browser.
app.js
var express = require('express');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'mywebsite'
});
connection.connect(function(error) {
if(!!error) {
console.log('Error');
} else {
console.log('Connected');
}
});
app.get('/', function(req, res) {
connection.query("SELECT Name FROM chat", function(error, rows, fields) {
if(!!error) {
console.log('Error in the query');
} else {
console.log('SUCCESS!\n');
console.log(rows);
res.send('Hello, ' + rows);
}
});
});
app.listen(1337);

Send it back with JSON.stringify
res.send('Hello, ' + JSON.stringify(rows))

Related

Where to place code to show data from MySQL to Handlebars?

Goal:
I am aiming to teach myself how to use Node JS, MySQL and express.
I'm struggling to understand where to place my code for loading MySQL data into HTML.
Let me show you the whole code.
app.js
var express = require('express');
var mysql = require('mysql');
var dotenv = require('dotenv');
var path = require('path');
var cookieParser = require('cookie-parser');
dotenv.config({path: './.env'});
var app = express();
// Connection to MySQL
var db = mysql.createConnection({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE
});
db.connect(function(error) {
if(error) {
console.log(error);
}
else{
console.log("Connected");
}
});
// Parse URL-Encoded bodies
app.use(express.urlencoded({extended: false}));
// Parse JSON bodies
app.use(express.json());
// Initialize a cookie
app.use(cookieParser());
// View engine to control HTML
app.set('view engine', 'hbs');
// Public dir
var publicDir = path.join(__dirname, './public');
app.use(express.static(publicDir));
// Define routes
app.use('/', require('./routes/pages'));
app.use('/auth', require('./routes/auth'));
app.listen(3000, function() {
console.log("Server is running on port 3000");
});
routes/pages.js
var express = require('express');
var authController = require('../controllers/auth');
var router = express.Router();
// Home
router.get("/", authController.isLoggedIn, function(req,res) {
res.render("index", {
user: req.user
});
});
// Register
router.get("/register", function(req, res) {
res.render("register");
});
// Login
router.get("/login", function(req, res) {
res.render("login");
});
// Profile
router.get('/profile', authController.isLoggedIn, function(req, res) {
if(req.user) {
res.render('profile', {
user: req.user
});
}
else {
res.redirect('login');
}
});
// Forum
router.get('/forums', authController.isLoggedIn, function(req, res) {
if(req.user) {
res.render('forums');
} else {
res.redirect('login');
}
});
// English Division //
// Premier League
router.get('/Leagues/EnglishDivision', authController.isLoggedIn, function(req, res) {
if(req.user) {
res.render('PremierLeague');
} else {
res.redirect('../../login');
}
});
module.exports = router;
routes/auth.js
var express = require('express');
var authController = require('../controllers/auth');
var router = express.Router();
// Register
router.post("/register", authController.register);
// Login
router.post("/login", authController.login);
// Logout
router.get('/logout', authController.logout);
module.exports = router;
controllers/auth.js
var mysql = require('mysql');
var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');
var {promisify} = require('util');
// Connection to MySQL
var db = mysql.createConnection({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE
});
// Register function
exports.register = function(req, res) {
console.log(req.body);
var {name, email, password, passwordConfirm} = req.body;
db.query("SELECT email FROM users WHERE email = ?", [email], function(error, result) {
if(error){
console.log(error);
}
if(result.length > 0) {
return res.render('register', {
message: 'That email is already in use'
})
} else if(password !== passwordConfirm) {
return res.render('register', {
message: 'Passwords do not match'
});
}
let hashedPassword = bcrypt.hashSync(password, 8);
console.log(hashedPassword);
// Insert user details into MySQL
db.query('INSERT INTO users set ?', {name: name, email: email, password: hashedPassword, dateJoined: new Date()}, function(error, result) {
if(error) {
console.log(error);
} else {
console.log(result);
return res.render('register', {
message: 'User registered'
});
}
});
});
}
// Login function
exports.login = function(req, res) {
try {
var {email, password} = req.body;
if(!email || !password) {
return res.status(400).render('login', {
message: 'Please provide an email and password'
});
}
db.query('SELECT * FROM users WHERE email = ?', [email], async function(error, result) {
console.log(result);
if(!result.length > 0 || !(await bcrypt.compare(password, result[0].password))) {
res.status(401).render('login', {
message: 'The email or password is incorrect'
});
}
else {
var id = result[0].id;
// Create a token
var token = jwt.sign({id}, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_IN
});
console.log("The token is " + token);
// Create a cookie
var cookieOptions = {
expires: new Date(
Date.now() + process.env.JWT_COOKIE_EXPIRES * 24 * 60 * 60 * 1000
),
httpOnly: true
}
// Set up a cookie
res.cookie('jwt', token, cookieOptions);
res.status(200).redirect("/");
}
});
} catch (error) {
console.log(error);
}
}
// Check if logged in
exports.isLoggedIn = async function(req, res, next) {
console.log(req.cookies);
if(req.cookies.jwt){
try {
// Verify the token
var decoded = await promisify(jwt.verify)(req.cookies.jwt, process.env.JWT_SECRET);
console.log(decoded);
// Check if user exist
db.query("SELECT id, name, email, password, date_format(datejoined, '%d/%m/%Y') as dateJoined FROM users WHERE id = ?", [decoded.id], function(error, result) {
console.log(result);
// If no result
if(!result) {
return next();
}
req.user = result[0];
return next();
});
}
catch (e) {
console.log(e);
return next();
}
} else{
next();
}
}
// Logout function
exports.logout = async function(req, res) {
res.clearCookie('jwt');
res.status(200).redirect('/');
}
Question
In my .hbs file called PremierLeague I'd like to load MySQL data in HTML format. Where in the code below I need to start?
Desired goal:
This is when the user clicks into view premier league
Foreach record in MySQL I'd like to add a new card for each record. I know how to use HandleBars {{some.data}}.
I just don't get where I code the query?
Does it needs to be in a controller or can it be in in the router.get(...?
Also how do I use {{#foreach}} correctly ?
You don't need any other specific controller, the right place to code the query is actually the route itself.
But before entering the core of your question, let's talk a while about your code.
I can see you are performing connection to database more than once, you could add database dedicated controller, something like:
controllers/db.js
var mysql = require('mysql');
var dotenv = require('dotenv');
dotenv.config({path: './.env'});
// Connection to MySQL
var db = mysql.createConnection({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE
});
function connect(done) {
db.connect(done);
}
module.exports = { db: db, connect: connect };
this let you access to the database instance from every file with just one line:
var db = require('./controllers/db').db;
than you could use the connect function in your app:
app.js
var express = require('express');
var db = require(./controllers/db);
var path = require('path');
var cookieParser = require('cookie-parser');
// set up your server
var app = express();
// Parse URL-Encoded bodies
app.use(express.urlencoded({extended: false}));
// Parse JSON bodies
app.use(express.json());
// Initialize a cookie
app.use(cookieParser());
// View engine to control HTML
app.set('view engine', 'hbs');
// Public dir
var publicDir = path.join(__dirname, './public');
app.use(express.static(publicDir));
// Define routes
app.use('/', require('./routes/pages'));
app.use('/auth', require('./routes/auth'));
// finally run your server only if you can connect to the database
db.connect(function(error) {
if(error) return console.log("Error connecting to the database:", error);
app.listen(3000, function() {
console.log("Server is running on port 3000");
});
});
you could also simplify you controllers/auth.js removing database connection stuff and using only the line to require your database controller.
Finally you can code your query:
routes/pages.js
var express = require('express');
var authController = require('../controllers/auth');
var db = require('../controllers/db').db;
var router = express.Router();
// Omissis... other routes
// Premier League
router.get('/Leagues/EnglishDivision', authController.isLoggedIn, function(req, res) {
// a good practice is first to handle possible exit cases to reduce nesting levels
if(! req.user) return res.redirect('../../login');
// this is actually the right place to perform queries
db.query('SELECT ...', [...], function(error, results) {
// once again first possible exit cases
if(error) return res.status(500).end(error.message)
res.render('PremierLeague', { results: results });
});
});
module.exports = router;
Last in your PremierLeague.hbs file you can handle the results in a #foreach directive.
Just pass your data when you render the view
router.get('/Leagues/EnglishDivision', authController.isLoggedIn, function(req, res) {
if(req.user) {
connection.query('SELECT * FROM EnglishDivision',function (err,results) {
if (err) throw err;
res.render('PremierLeague',{data: results});
});
} else {
res.redirect('../../login');
}
});
then in the .hbs file
{{#each data}}
<div class="card">
<h3>{{this.someData}}</h3>
<h2>{{this.someData}}</h2>
</div>
{{/each}}

Node.JS, Get function & Connection to XAMPP DB doesn't work

I'm using the XAMPP software as a local DB and trying to get into the get function at the below with no success.
In addition, I can not see any console comments as well:
Web error
Node.js
Thank you for your help!!
var express = require('express');
const cors = require('cors');
var app = express();
var corsOptions=
{
origin: 'http://localhost:3000',
optionsSuccessStatus: 200,
allowHeaders: ['sessionId', 'Content-Type'],
exposedHeaders: ['sessionId'],
credentials: true,
}
app.use(cors(corsOptions));
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "apptxtproject"
});
app.get("/getnetworks"), (req,res)=>{
con.query(`SELECT * FROM appadtxt`, function (err, result, fields) {
if (err) throw err;
console.log(result)
})
}
app.listen(4000, function () {
console.log('Haydeeeeee!!!');
})
In your app.get you have a bad syntax error try this:
app.get("/getnetworks", (req, res) => {
con.query(`SELECT * FROM appadtxt`, function(err, result, fields) {
if (err) throw err;
console.log(result);
});
});

Cannot enqueue Handshake after already enqueuing a Handshake. for get data with http client and server

Client side code with angular 4:
this.http.get('http://localhost:8080').subscribe(data => {
console.log(data);
});
Server Side Code getting data from mysql:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "mydb"
});
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
con.connect(function(err) {
if (err){
res.write(err);
res.end();
console.log(err);
} else {
con.query("SELECT * FROM minister", function (err, result) {
if (err) {
res.write(err);
res.end();
console.log(err);
}
else {
res.write(JSON.stringify(result));
res.end();
}
});
}
})
}).listen(8080);
Getting data on localhost:8080 in browser but not sending data to html client site any on can help me? any thing wrong in my code

Nodejs: Post method url body parser shows undefined

I want to use url post params to execute mysql query. I am getting error during mysql command when I post through postman. I dont know what is problem with this code. Here is my code
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
var md5 = require('MD5');
var con = mysql.createConnection({
host: "localhost",
user: "shoaib",
password: "",
database: "watch"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.post('/',function(req, res) {
con.connect(function(err) {
var query = "Select * From user Where email=? AND password=?";
var table = [req.body.email,req.body.password ];
console.log(req.body);
query = mysql.format(query, table);
con.query(query, function (err, rows) {
if (err) {
res.json({ "Error": true, "Message": "Error executing MySQL query" });
} else if(rows!=0) {
res.json({ "Error": false, "Message": "Success","Users": rows });
} else {
res.json({ "Error": true,});
}
});
});
});
app.use('/api', router);
app.listen(port);
console.log('Magic happens on port ' + port);
Node is working perfectly but when I execute command url I face error.
Make sure on your request that you set the Content-Type header to application/json or application/x-www-form-urlencoded since your app supports either. Without a Content-Type header with either of these values body-parser will not read the request body and res.body will be undefined.
Example POST Request with Content-Type: application/json
const {request} = require('http')
const requestBody = {email: 'abc#gmail.com', password: 'abcdef123456'}
const jsonPostRequest = request({
method: 'POST',
host: 'localhost',
port: 8080,
path: '/api/',
headers: {'Content-Type': 'application/json'}
}, res => {
let chunks = ''
// Handle Response Chunk
res.on('data', chunk => (chunks += chunk))
// Handle Response Ended, print response body
res.on('end', () => console.log(chunks))
})
jsonPostRequest.write(requestBody)
jsonPostRequest.end()

Why doesn't this code return json data?

I'm trying to fetch data from database using Node.js and MySQL.
Here's what I'm trying:
var app=require('express')();
var bodyParser=require("body-parser");
var mysql=require('mysql');
var http=require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end();
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
var connection=mysql.createConnection({
host: 'localhost',
user: 'root',
password: "",
database: 'books'
});
connection.connect(function(err) {
if ( !err ) {
console.log("Connected to MySQL");
} else if ( err ) {
console.log(err);
}
});
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.get('/book', function(req, res){
var data={
'error': 1,
'Books': ""
};
connection.query("SELECT * FROM book", function(err, rows, fields){
if(rows.length!=0){
data['error']=0;
data['Books']=rows;
res.json(data);
}else{
data['Books']='No books found';
res.json(data);
}
});
});
When I execute node server.js it shows following output in the cmd:
Server running at http://127.0.0.1:8081/
Connected to MySQL
But when I visit to http://127.0.0.1:8081/book, it doesn't display any output.
NOTE: My XAMPP Apache server and MySQL are started.
The problem is, I believe, that you're using two different and redundant web servers. One is http and the other is app (ie. Express). Only http is actually listening on port 8081.
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end();
}).listen(8081);
Since all it ever does is write a text/plain header and exit you'll get a blank page no matter what path you try to access.
The other one, app, never listens on a port. So all that app code sets up a server that can't be accessed.
So remove all the http stuff, you don't need it. Express handles this for you. Then call app.listen(8081).
var app = require('express')();
var bodyParser = require("body-parser");
var mysql = require('mysql');
var connection=mysql.createConnection({
host: 'localhost',
user: 'root',
password: "",
database: 'books'
});
connection.connect(function(err) {
if ( !err ) {
console.log("Connected to MySQL");
} else if ( err ) {
console.log(err);
}
});
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.get('/book', function(req, res){
var data={
'error': 1,
'Books': ""
};
connection.query("SELECT * FROM book", function(err, rows, fields){
if(rows.length!=0){
data['error']=0;
data['Books']=rows;
res.json(data);
}else{
data['Books']='No books found';
res.json(data);
}
});
});
app.listen(8081, function () {
console.log('Server running on port 8081');
});