Node MySQL Connection Not Working - mysql

I am new to Node an Express, I have this code which simply connects to a MySQL Db...Nothing is happening when I try to 127.0.0.1:9080. I'm doing something wrong but can't figure out what...nothing in the console no errors, tried in chrome, FF, Safari and IE...Any ideas.
var http = require('https');
var express = require('express');
var app = express();
var hbs = require('hbs');
var path = require('path');
var mysql = require('mysql');
app.set('view engine', 'html');
app.engine('html', hbs.__express);
//mysql connect
var connection = mysql.createConnection({
host : 'mysql://root#localhost/mydb2',
user : 'someone',
password : 'secret'
});
app.get('/', function(request, response) {
connection.query('select * from sometable', function(err, rows){
if (err) throw err;
console.log("Test01=" + row[0].toString());
});
app.listen(9080);
});

You need to write something in the response to see it on the browser.
Add this line before console.log() statement.
response.json(rows);

Related

Nodejs Expess Script Unable to Create the Mysql Database Table

I created node js express applications with express generator. I am trying to create table by executing database script called db.js . This script is located into database folder . I am able to run the server but when I tried to execute the script by using C:\Users\Khundokar Nirjor\Desktop\Nodejs Resources\shopping-cart\database>node db.js
C:\Users\Khundokar Nirjor\Desktop\Nodejs Resources\shopping-cart\database>
It is not able to create the table or inserting records.
Here is my app.js code .
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var expressHbs = require('express-handlebars');
var mysql = require('./database/db');
var app = express();
require('./database/db');
// view engine setup
app.engine('.hbs',expressHbs({defaultLayout: 'layout' , extname: '.hbs'}));
app.set('view engine', '.hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
//app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Here is the db.js code .
var mysql = require('mysql');
//var app = express();
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "shopdb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "CREATE TABLE products (imagepath VARCHAR(255), tittle VARCHAR(255), descriptions VARCHAR(255),price VARCHAR(255))";
var sql1 = "INSERT INTO products (imagepath, tittle,descriptions,price) VALUES ?";
var values = [
['https://upload.wikimedia.org/wikipedia/en/5/5e/Gothiccover.png', 'Gothic Veido Game','Awesome Game !!!!','25'],
['https://upload.wikimedia.org/wikipedia/en/5/5e/Gothiccover.png', 'Gothic Veido Game','Awesome Game old !!!!','100'],
['https://upload.wikimedia.org/wikipedia/en/5/5e/Gothiccover.png', 'Gothic Veido Game','Awesome Game New !!!!','120'],
['https://upload.wikimedia.org/wikipedia/en/5/5e/Gothiccover.png', 'Gothic Veido Game','Awesome Game !!!!','26'],
];
con.query(sql, sql1,[values], function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
});
con.destroy();
You should enable multistatement true while creating a connection as you are running multiple statements.change your configuration options as below:
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "shopdb",
multipleStatements: true
});
Refer this :
https://github.com/mysqljs/mysql#multiple-statement-queries

connect nodejs to mysql

I have following code that connect nodejs to mysql. When I run it the first time it work the data print out to the page but when I refresh the page it tell 'This site can’t be reached' 'localhost refused to connect.' I don't understand why I can connect to server only the first time. I use url as localhost:3000/car
var express = require('express');
var app = express();
app.use(express.static(__dirname));
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'joeM',
password : 'versus',
database : 'joe'
});
app.get('/car', function(req, res){
connection.connect();
connection.query('SELECT * FROM test1', function(err, rows, fields) {
if (err) throw err;
var print = '<ol>';
for( var i = 0; i<rows.length; i++){
print +=('<li>ID:' + rows[i].id + ' Brand:' + rows[i].brand +'</li>' );
}
print += '</ol>';
res.send(print);
connection.end();
});
});
app.listen(3000, function(){
console.log('Magic Happen at port: 3000');
});
dont use connection.connect(); in every request and set it out of request block

Gets Error when adding MySQL information in server.js when creating RESTful API with Express

I was following instructions to build a RESTful API with Express and MySQL(*1)
But when I change
app.listen(port); //excutable, GET returns welcome message
into
orm.initialize(WConfig.config,function(err,models){
...
in the part 2 of(*1), which is adding MySQL information into server.js,
I gets the following on Node.JS command prompt:
TypeError: Cannot read property 'bear' of undefined
Because this is the first attempt in building RESTful API, I'm not sure what to do to fix it. Help please! Any idea is appreciated.
full code of server.js:
// server.js
var util = require('util');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var Waterline = require('waterline');
var Bear = require('./app/models/bear');
var WConfig = require('./app/config/waterline');
var orm = new Waterline();
orm.loadCollection(Bear);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.get('/', function(req, res) {
res.json({ message: 'hello! welcome to our api!' });
});
app.use('/api', router);
// express deprecated res.json(obj,status): use res.status(status).json(obj) instead
router.route('/bears')
.post(function(req,res) {
app.models.bear.create(req.body,function(err,model) {
if(err) return res.status(500).json({ err,err });
res.json(model); //res.json(model) , guess: res.status(200).json(model);
console.log(util.inspect(model));
});
});
//gets error if I change it to following
//
orm.initialize(WConfig.config,function(err,models){
if(err) throw err;
app.models = models.collections;
//app.set('models',models.collections);
app.connections = models.connections;
app.listen(port);
console.log('Magic happens on port ' + port);
});
reference:
1.Create Restful API with Express and waterline (in Chinese)
https://segmentfault.com/a/1190000004996659#articleHeader2
2.Build a RESTful API Using Node and Express 4
https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4

How to connect static HTML and CSS files to Node.js application?

I try to show a (static) HTML webpage via Heroku. I have followed this tutorial: https://www.youtube.com/watch?v=gAwH1kSODVQ but after many attempts it is still not working.
I'm rather new to coding, so if you can give concrete examples that would be great!
The following files have been pushed to heroku:
server.js
package.json
Procfile.js
(folder) public with index.html, main.css
//Server.js file:
var express = require('express'); //require express module in server.js file
var app = express();
var mongojs = require('mongojs');
var db = mongojs('birthdaylist', ['birthdaylist']);
var bodyParser = require('body-parser');
var http = require('http');
var port = Number(process.env.PORT || 3000);
app.use(express.static(__dirname + '/public')); //connect to html file
app.use(bodyParser.json());
app.get('/birthdaylist', function(req, res) {
console.log("The server has received a GET request.")
db.birthdaylist.find(function(err, docs){
console.log(docs);
res.json(docs);
});
});
app.post('/birthdaylist', function(req, res){
console.log(req.body);
db.birthdaylist.insert(req.body, function (err, doc){
res.json(doc);
});
});
app.delete('/birthdaylist/:id', function(req, res){
var id = req.params.id;
console.log(id);
db.birthdaylist.remove({_id: mongojs.ObjectId(id)}, function(err, doc){
res.json(doc);
});
});
app.listen(port, function () {
});
you should use:
app.listen(%PORT_NUMBER%, function () {
// some code here
});
Instead of:
var server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type':'text/html'});
res.end('<h6>Hello worldsfasfd!</h6>');
});

How to start a session when user logs in and end session when user logs out

I am new to node.js. How should I start a session when the user logs in and end the session when the user logs out?
Please note the environment of this application:
I'm using Windows
NPM, Express
MySQL for Node
This is my app.js file:
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var customers = require('./routes/customers');
var app = express();
var connection = require('express-myconnection');
var mysql = require('mysql');
app.set('port', process.env.PORT || 4300);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.use(
connection(mysql,{
host: 'localhost',
user: 'root',
password : '',
//port : 3306, //port mysql
database:'nodejs'
},'pool') //or single
);
app.get('/', customers.login);
app.get('/login', customers.login);
app.post('/login', customers.checklogin);
app.get('/logout', customers.logout);
app.use(app.router);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
And this is routing File (customers.js):
exports.logout = function(req, res){
var messages = '';
res.render('login',{page_title:"Login",message: messages});
};
exports.checklogin = function(req,res){
var loginInput = JSON.parse(JSON.stringify(req.body));
req.getConnection(function (err, connection) {
var username = loginInput.username;
var pswd = loginInput.pswd;
var query = connection.query("SELECT * FROM users WHERE username = ? AND pswd = ? ",[username,pswd], function(err,rows)
{
var messages = 'Username/Password is wrong. Try again.';
res.render('login',{page_title:"Login",message: messages});
});
});
};
It's really simple if you're using sessions.
app.post('/login', function(req, res, next) {
if(err) return next(err)
if(authenticate(req.body.username, req.body.password) req.session.user = {login: true, username: req.body.username }
res.render(<Some file you want to send to user>);
}
app.get('/logout', function(req, res, next) {
if(err) return next(err)
req.session.user = {login: false, username = null}
res.render(<Some file you want to send to user>);
This way you can login a user and set their username for later use in sessions and log them out in the same way.