Node/Express + MySQL: Inserts not displaying instantly - mysql

I have a form called #add_blog_post with the action "/mysql_test/add_blog_post" and method of "POST"
Jade markup:
form#add_blog_post(action="/mysql_test/add_blog_post" method="POST")
This form executes the following code in my app.js:
app.post('/mysql_test/add_blog_post', function(req, res) {
var author = req.body.author;
var date = req.body.date;
var title = req.body.title;
var body = req.body.body;
var blog_insert_query = "insert into 332project.blog(author,date,title,body) values(";
blog_insert_query += ("'"+author+"'"+","); blog_insert_query += ("'"+date+"'"+","); blog_insert_query += ("'"+title+"'"+","); blog_insert_query += ("'"+body+"'"+")");
var connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS
});
connection.connect(function(err) { /*error?*/ });
var result;
var query = connection.query(blog_insert_query, function(err, result) {
res.redirect('/mysql_test');
});
});
The blog post insert works just fine but the website takes a while for the insert to be displayed from the select statement on /mysql_test.
Here is my route:
var express = require('express');
var router = express.Router();
var db_calls = require('../db.js');
var connection = db_calls.connect();
connection.connect(function(err) { /*error?*/ });
var result;
var query = connection.query("select * from 332project.blog order by id desc", function(err, rows, fields) {
connection.end();
if (!err) {
result = rows;
}
});
router.get('/', function(req, res, next) {
res.render('mysql_test', {
result: result
});
});
module.exports = router;
What gives? It almost seems like a caching issue. I'd really like for my create/update operations to be instantly visible in my application.
Source code: https://github.com/harwoodjp/learning-express

Your problem is probably that you're not calling connection.end() per the docs.

Related

nodejs server app.post issue XML Parsing Error: syntax error Location: http://localhost:3000/get_messages Line Number 1, Column 1:

I followed a tutorial on YouTube to create a private user to user chat.
https://www.youtube.com/watch?v=Ozrm_xftcjQ
Everything on the chat works accept that i keep getting this Error:
XML Parsing Error: syntax error Location: http://localhost:3000/get_messages Line Number 1, Column 1:
using firefox developer edition and chrome. if i click the stack trace link i get the following xml error:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /get_messages</pre>
</body>
</html>
but i have no GET calls at all..
The code looks as follows:
server.js file
var port = process.env.PORT || 3000;
//creating express instance
var express = require("express");
var app = express();
//creating http instance
var http = require("http").createServer(app);
//app.use(express.static(__dirname));
//creating socket instance
var io = require("socket.io")(http);
//create body parser instance
var bodyParser = require("body-parser");
app.use(bodyParser.json());
//enable url encode for POST requests
app.use(bodyParser.urlencoded({ extended : true }));
//create instance of mysql
var mysql = require('mysql');
//create mysql connection
// connectionLimit: 100,debug: true
var connection = mysql.createConnection({
host: 'localhost',
user: 'xxx',
password: 'xxx',
database: 'chatio'
});
connection.connect(function(error){
if(error){
console.log(error);
return;
}
console.log('database connected');
})
//enable header request for post requests
app.use(function(request, result, next){
result.setHeader("Access-Control-Allow-Origin", "*");
next();
})
//create api to return all messages
app.post("/get_messages", function(request, result){
console.log(request);
console.log(result);
connection.query("SELECT * FROM chat_messages WHERE (`from_id` = '"+request.body.sender+"' AND `to_id` = '"+request.body.receiver+"') OR (`from_id` = '"+request.body.receiver+"' AND `to_id` = '"+request.body.sender+"')", function(error, messages){
if(error){
console.log(error);
return;
}
console.log(messages);
//response will be in JSON
result.end(JSON.stringify(messages));
});
})
io.on("connection", function(socket){
socket.on("send_message", function(data){
//send event to receiver
var socketId = users[data.receiver];
io.to(socketId).emit("new_message", data);
//save in database
connection.query("INSERT INTO chat_messages (`from_id`,`to_id`,`message`) VALUES ('"+data.sender+"', '"+data.receiver+"', '"+data.message+"')", function(error, result){
if(error){
console.log(error);
return;
}
console.log('message saved');
});
})
})
http.listen(port, function(){
console.log("server started");
})
inde.php file code as follows:
//creating io connection
var io = io("http://localhost:3000");
var receiver = "johnny";
var sender = "steven";
function onUserSelected(){
$.ajax({
url: "http://localhost:3000/get_messages",
method:"POST",
cache: false,
data: {
"sender" : sender,
"receiver" : receiver
},
dataType: "json",
success: function(response){
var messages = response; //JSON.parse();
var html = "";
for(var i = 0; i < messages.length; i++){
html += "<li>" +messages[i].from_id + " says: " + messages[i].message + "</li>";
document.getElementById('messages').innerHTML += html;
}
}
});
return;
}
}
i figured it out..
the problem comes from this line:
result.end(JSON.stringify(messages));
I dont exactly understand why, but i changed it to
result.send(JSON.stringify(messages));
and now the bug is gone

sending json data response

I am trying to send a JSON response via HTTP but unfortunately, I don't see any response, I cant understand why really.
It looks like the response variable is not being sent.I am not sure the problem is that it is a JSON object or the way I am sending it.I am new to web development.
The requirement is to help user see the time and the name of the file which was usccessfully sent through.
var express = require('express');
var fs = require('fs');
var cors = require('cors');
var bodyParser = require('body-parser');
var multer = require('multer');
var app = express();
var upload = multer({ dest: 'uploads/' });
var Client = require('ssh2').Client;
const request = require('request');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors());
app.get('/', function(req, res){
console.log('GET /');
//var html = '<html><body><form method="post" action="http://localhost:3000">Name: <input type="text" name="name" /><input type="submit" value="Submit" /></form></body>';
var html = fs.readFileSync('index.html');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
});
app.post('/', upload.single('file'), function(req, res){
var response;
var time;
console.log('POST /');
console.dir(req.body);
// console.log(req.body.filename);
fs.writeFile('./uploads/' + req.body.filename, req.body.file,
function(err) { console.log(err)});
var conn = new Client();
conn.on('ready', function() {
console.log('Client :: ready');
conn.sftp(function(err, sftp) {
if (err) throw err;
// sftp.fastPut('./uploads/' + req.body.filename, '/data/' +
req.body.filename, function (err) {
// if (err) {
// console.log(err);
// throw err;
// }
// });
sftp.readdir('data', function(err, name) {
if (err) throw err;
console.dir(name);
var infoList = JSON.parse(JSON.stringify(name));
for(var index in infoList) {
var value = infoList[index];
time = value.attrs.mtime;
console.log(value.filename);
console.log(time);
response = JSON.stringify(value.filename);
}
conn.end();
});
});
}).connect({
host: 'ftp.amadeus.net',
port: 15022,
username: 'wtl001',
password: 'Wyamp309$'
});
res.writeHead(200, {'Content-Type': 'application/json', "Access-Control-
Allow-Origin": "*"});
res.json(response);
res.end("EOF");
});
port = 12811;
app.listen(port);
console.log('Listening at http://localhost:' + port);

Connecting to database in Node.js from routes

I'm working on a express server and am having trouble accessing my database from a route file I have set up for users. When I attempt to make a get request I receive this as an error.
"code": "ER_NO_DB_ERROR",
"errno": 1046,
"sqlState": "3D000",
"index": 0
I have been trying to look for a solution online but most of the answers suggest requiring db.js file everywhere which I already do. I have a feeling I need to pass the connection I made in app.js around but I am not sure how to do this. The relevant parts of my files are below. Database login info has been redacted, I do get a successful connection in app.js. I'm fairly new to this so any help would be appreciated, specifically if there is a better way to use the pool implemented in db.js.
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var mysql = require('mysql')
var app = express();
var users = require('./routes/users');
var media = require('./routes/media');
var tv = require('./routes/tv');
var movies = require('./routes/movies');
var db = require('./db.js')
var connection = mysql.createConnection({
port: '3306',
host: '*********************',
user: '********',
password: '******'
})
db.connect(function(err) {
if (err) {
console.log('Unable to connect to MySQL.')
process.exit(1)
} else {
console.log('Successfully connected')
}
})
app.use('/api', users);
models/user.js
var db = require('../db.js');
var passwordHash = require('password-hash');
exports.getAll = function(done) {
db.get().query('SELECT * FROM users', function (err, rows) {
if (err) return done(err)
done(null, rows)
})
}
routes/users.js
var express = require('express');
var router = express.Router()
var user = require('../models/user');
var db = require('../db.js');
//this doesn't prInt anything currently. This is prompting me to believe I somehow
//need to pass a connection object or am using the pool properly.
console.log(db.get());
router.route('/users').get(function(req, res) {
user.getAll(function(err, users) {
if (err) {
return res.send(err);
}
res.json(users);
});
});
db.js
//this is taken mostly from a tutorial I found online
var mysql = require('mysql')
, async = require('async')
var PRODUCTION_DB = 'app_prod_database'
, TEST_DB = 'app_test_database'
exports.MODE_TEST = 'mode_test'
exports.MODE_PRODUCTION = 'mode_production'
var state = {
pool: null,
//mode: null,
}
exports.connect = function(done) {
state.pool = mysql.createPool({
port: '3306',
host: '***************',
user: '*********',
password: '*******'
//database: mode === exports.MODE_PRODUCTION ? PRODUCTION_DB : TEST_DB
})
//state.mode = mode
done()
}
exports.get = function() {
return state.pool
}
exports.fixtures = function(data) {
var pool = state.pool
if (!pool) return done(new Error('Missing database connection.'))
var names = Object.keys(data.tables)
async.each(names, function(name, cb) {
async.each(data.tables[name], function(row, cb) {
var keys = Object.keys(row)
, values = keys.map(function(key) { return "'" + row[key] + "'" })
pool.query('INSERT INTO ' + name + ' (' + keys.join(',') + ') VALUES (' + values.join(',') + ')', cb)
}, cb)
}, done)
}
exports.drop = function(tables, done) {
var pool = state.pool
if (!pool) return done(new Error('Missing database connection.'))
async.each(tables, function(name, cb) {
pool.query('DELETE * FROM ' + name, cb)
}, done)
}
Either supply a valid database in the createConnection...
var connection = mysql.createConnection({
port: '3306',
host: '*********************',
user: '********',
password: '******',
database: 'mydatabase'
And/or, qualify the table name with the name of the database in the query:
db.get().query('SELECT * FROM mydatabase.users',
^^^^^^^^^^^
What it looks like is happening in the current code, a connection is established to the MySQL Server. But no USE mydatabase statement has been executed. When the SQL statement SELECT ... FROM users is executed, MySQL doesn't know which database the users is supposed to reference. (That table could exist in multiple databases containing a table or view named users.)
That's what's causing the 1046 No database selected error.

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

Whats wrong with this express code?

Hello i am trying to check two mysql values and if its matching anything in the database it needs to generate a token but it does not seem to work :(
Everytime i run this code i get a connection time out:
var express = require('express');
var router = express.Router();
var mysql = require("mysql");
var randomstring = require("randomstring");
/* GET users listing. */
router.get('/', function(req, res, next) {
// First you need to create a connection to the db
var connection = mysql.createConnection({
host: "localhost",
user: "segfault",
password: "wnk9ctte2endcKzBKtre7auE",
database: "segfault"
});
connection.connect();
var input_user = req.body.username;
var input_pass = req.body.password;
var token = randomstring.generate(12);
connection.query('SELECT username FROM segfault.users AS username', function(err, rows, fields) {
if (err) throw err;
for(var i in rows){
username = rows[i].username;
if(input_user == username){
connection.query('SELECT password FROM segfault.users AS password', function(err, rows, fields) {
if(rows[i].password == input_pass){
res.send("OK: "+ token);
console.log("OK:" + token)
}
});
}
}
});
connection.end();
});
module.exports = router;
tell me please what i am dooing wrong!
You close the connection to the database without waiting for the result of the query.
Move connection.end(); inside callback after the res.send.