So i have next test code, which i found here
// Include http module,
var http = require('http'),
// And mysql module you've just installed.
mysql = require("mysql");
// Create the connection.
// Data is default to new mysql installation and should be changed according to your configuration.
var connection = mysql.createConnection({
user: "root",
password: "pass",
database: "db_name"
});
// Create the http server.
http.createServer(function (request, response) {
// Attach listener on end event.
request.on('end', function () {
// Query the database.
connection.query('SELECT * FROM your_table;', function (error, rows, fields) {
response.writeHead(200, {
'Content-Type': 'x-application/json'
});
// Send data as JSON string.
// Rows variable holds the result of the query.
response.end(JSON.stringify(rows));
});
});
// Listen on the 8080 port.
}).listen(8080);
i download mysql module, install mysql of course, and run next script, and get no results. Can you give me advice what i do wrong?
When i trying to load
http://localhost:8080/
browser trying to load page several minutes, and also no result.
Thanks.
update
I think you forgot
connection.connect()
I'm using these for while now and it works fine for me.
// Include http module,
var http = require('http'),
// And mysql module you've just installed.
mysql = require("mysql");
// Create the connection.
// Data is default to new mysql installation and should be changed according to your configuration.
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "pass",
database: "db_name"
});
connection.connect();
// Create the http server.
http.createServer(function (request, response) {
// Attach listener on end event.
request.on('end', function () {
// Query the database.
connection.query('SELECT * FROM your_table;', function (error, rows, fields) {
response.writeHead(200, {
'Content-Type': 'x-application/json'
});
// Send data as JSON string.
// Rows variable holds the result of the query.
response.end(JSON.stringify(rows));
});
});
// Listen on the 8080 port.
}).listen(8080);
Few previous answers that should help you
Express.JS + Node-Mysql and 1 connection per http request
How to query mysql before starting http server in nodejs
get simple info from db into a node.js http server response
to use pools in mysql
Node.js MySQL Needing Persistent Connection
A more little complex solution separate your code into files and put the db code either in db.js or in reponse handler or router.
My code is using pools.
Save to the five files
then run npm install
e.g
(please excuse the terrible formatting)
// requestHandlers.js
// request handler with mysql code
var mysql = require("mysql");
var Query1 = "SELECT * from Tablexyz WHERE xx = 'doh'";
var body = '<html>'+
'<head>'+
'<meta http-equiv="Content-Type" content="text/html; '+
'charset=UTF-8" />'+
'</head>'+
'<body>'+
'<h1> Query </h1>';
var body1 = '</body>'+
'</html>';
var pool = mysql.createPool({
host : 'host',
user : 'dbuser',
password : "pword",
database : 'database',
connectionLimit: 10,
queueLimit: 10
});
function qquery(callback){
console.log('in qquery');
pool.getConnection(function(err, connection) {
pool.query( Query1 , function(err, rows ,fields) {
if (err) {
return callback(new Error("An error has occured" + err));
}
if (rows.length > 0){
callback( rows);
connection.release();
}
});
});
}
function start(response) {
console.log("Request handler 'start' was called.");
qquery( function (rows , err) {
if (err) {
console.log(err);
}
else{
console.log(rows);
response.writeHead(200, {"Content-Type": "text/html"});
response.write(body);
response.write( 'query: ' + JSON.stringify( rows ) );
response.write(body1);
response.end();
}
});
}
exports.start = start;
///////////////////////////////////- new file
//server.js
var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(handle, pathname, response);
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
///////////////////////////////////-new file
// router.js
function route(handle, pathname, response) {
console.log("About to route a request for " + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname](response);
} else {
console.log("No request handler found for " + pathname);
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not found");
response.end();
}
}
exports.route = route;
///////////////////////////////////- new file
//index.js
var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");
var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
server.start(router.route, handle);
///////////////////////////////////- new file
//package.json
{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies":
{
"express": "3.4.0",
"jade": "*",
"stylus": "*",
"mysql": "*"
}
}
#Ishikawa Yoshi
use a callback
// Include http module
var http = require('http')
// And mysql module you've just installed.
mysql = require("mysql");
var Query1 = "SELECT * from Tablexyz WHERE xx = 'doh'";
var connection = mysql.createConnection({
host : 'host',
user : 'dbuser',
password : "pword",
database : 'database',
});
connection.connect();
function getData(callback){
console.log('in getData');
connection.query( Query1 , function(err, rows ,fields) {
if (err) {
return callback(new Error("An error has occured" + err));
}
if (rows.length > 0){
callback( rows);
}
});
}
// Create the http server.
http.createServer(function (request, response) {
// Attach listener on end event.
// Query the database.
getData(function (rows , err) {
if (err) {
console.log(err);
}
else{
response.writeHead(200, {"Content-Type": "text/html"});
response.write( 'query: ' + JSON.stringify( rows ) );
response.end();
}
});
// Listen on the 4001 port.
}).listen(4001);
Related
I included the socket.io.js in client and also included the custom created socket.js for getting the responses from websocket server to client,when i loading this page in browser automatically stopped the websocket server and in browser console tells WebSocket connection to 'ws://localhost:8000/socket.io/?EIO=3&transport=websocket&sid=2p1ZYDAflHMHiL70AAAA' failed: Connection closed before receiving a handshake response
user defined socket.js code is given below
var socket = io();
var actionItems = []
var beginTakingAction = false
var strOut;
socket.on('transcript', function(x) {
var div = $('div.transcription')
div.html(x);
console.log("transcript " + x);
if (!scrolling) {
div.scrollTop(div[0].scrollHeight);
}
})
socket.on('action', function(x) {
console.log('sending action',x);
actionItems.push(x)
$('div.action').html(actionItems[actionItems.length-1]);
})
socket.on('sentiment', function(x) {
sentimentChart.update(x)
})
socket.on('nlp', function(x) {
wordLengthDistChart.update(x.wordLenghDist);
posTagDistChart.update(x.posTagDist);
})
socket.on('keywords', function(x) {
keywordChart.update(x)
})
socket.on('status', function(status) {
$('div.status').html("status: " + status);
if (status == "connected") {
sentimentChart.reset()
keywordChart.reset()
wordLengthDistChart.reset()
posTagDistChart.reset()
$('div.transcription').html('');
}
})
please give any suggesstions??
my server code is given below
require('dotenv').config()
var WebSocketServer = require('websocket').server;
var http = require('http');
var HttpDispatcher = require('httpdispatcher');
var dispatcher = new HttpDispatcher();
const fs = require('fs');
const winston = require('winston')
winston.level = process.env.LOG_LEVEL || 'info'
var AsrClient = require('./lib/asrClient')
var asrActive = false
var myAsrClient;
var engineStartedMs;
var connections = []
//Create a server
var server = http.createServer(function(req, res) {
handleRequest(req,res);
});
// Loading socket.io
var io = require('socket.io').listen(server);
// When a client connects, we note it in the console
io.sockets.on('connection', function (socket) {
winston.log('info','A client is connected!');
});
var wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: true,
binaryType: 'arraybuffer'
});
//Lets use our dispatcher
function handleRequest(request, response){
try {
//log the request on console
winston.log('info', 'handleRequest',request.url);
//Dispatch
dispatcher.dispatch(request, response);
} catch(err) {
console.log(err);
}
}
dispatcher.setStatic('/public');
dispatcher.setStaticDirname('public');
dispatcher.onGet("/", function(req, res) {
winston.log('info', 'loading index');
winston.log('info', 'port', process.env.PORT)
fs.readFile('./public/index.html', 'utf-8', function(error, content) {
winston.log('debug', 'loading Index');
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});
// Serve the ncco
dispatcher.onGet("/ncco", function(req, res) {
fs.readFile('./ncco.json', function(error, data) {
winston.log('debug', 'loading ncco');
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(data, 'utf-8');
});
});
dispatcher.onPost("/terminate", function(req, res) {
winston.log('info', 'terminate called');
wsServer.closeAllConnections();
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end();
});
wsServer.on('connect', function(connection) {
connections.push(connection);
winston.log('info', (new Date()) + ' Connection accepted' + ' - Protocol Version ' + connection.webSocketVersion);
connection.on('message', function(message) {
if (message.type === 'utf8') {
try {
var json = JSON.parse(message.utf8Data);
winston.log('info', "json", json['app']);
if (json['app'] == "audiosocket") {
VBConnect();
winston.log('info', 'connecting to VB');
}
} catch (e) {
winston.log('error', 'message error catch', e)
}
winston.log('info', "utf ",message.utf8Data);
}
else if (message.type === 'binary') {
// Reflect the message back
// connection.sendBytes(message.binaryData);
if (myAsrClient != null && asrActive) {
winston.log('debug', "sendingDate ",message.binaryData);
myAsrClient.sendData(message.binaryData)
}
}
});
connection.on('close', function(reasonCode, description) {
winston.log('info', (new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
wsServer.closeAllConnections();
});
});
wsServer.on('close', function(connection) {
winston.log('info', 'socket closed');
if (asrActive) {
io.sockets.emit('status', "disconnected");
winston.log('info', 'trying to close ASR client');
myAsrClient.close();
myAsrClient = null;
asrActive = false;
}
else {
winston.log('info', 'asr not active, cant close');
}
})
wsServer.on('error', function(error) {
winston.log('error', 'Websocket error', error);
})
var port = process.env.PORT || 8000
server.listen(port, function(){
winston.log('info', "Server listening on :%s", port);
});
I am creating a Rest API in Node.js and Express. It connects with remote HANA database & execute one query. Now I want to stream HTTP response so that I can send it to browser into chunks, rather than sending it completely since it's a very large data.
I tried something which is giving me no output. I don't know the reason. If I send the complete response to browser using response.send (data), it's working fine. But streaming is now working.
I have added code snippet below.
const express = require("express");
const APP = express();
const HANA_DB = require('hdb');
const BODY_PARSER = require("body-parser");
start();
function start() {
startServer();
initializeExpress();
APP.get("/data", function(request, response) {
var connection = HANA_DB.createClient({
host : "hostname",
port : "port",
user : "username",
password : "password"
});
connection.on('error', function (error) {
console.log("Error in database connection...");
});
connection.connect(function (error) {
if (error) {
console.log("Error in database connection...");
return;
}
var query = "SELECT * FROM TableName";
connection.exec(query, function(error, result) {
if(error) {
response.send("Getting error while fetching result...");
return;
}
//response.send(data);
var datalength = 0;
request.on('data', function(chunk) {
datalength += chunk.length;
console.log("DATA EVENT: " + datalength);
response.send(datalength);
})
.on('end', function() {
console.log("END EVENT: " + datalength);
response.send(datalength);
});
});
});
});
};
function initializeExpress() {
APP.all('/*', function(request, response, next) {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers", "X-Requested-With");
response.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
response.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
APP.use(BODY_PARSER.json());
APP.use(BODY_PARSER.urlencoded({ extended: true }));
};
function startServer(config) {
var server = APP.listen("8081", function(error) {
if(error) {
console.log("Unable to connect to 127.0.0.1:8081");
return;
}
console.log("Server is listening at - 127.0.0.1:8081");
});
};
I think the logic you are using is wrong for the streaming the data.
Use res.write instead of res.send and you also have to read streaming data from your database instead of one time connection.exec
I am giving you an example code where you will get some idea about streaming data in Expressjs.
var http = require( 'http' );
http.createServer( function ( req, res ) {
res.writeHead( 200, {
'Content-Type': 'text/plain; charset=utf-8',
'Transfer-Encoding': 'chunked',
'X-Content-Type-Options': 'nosniff'
} );
res.write( 'Beginning\n' );
var count = 10;
var io = setInterval( function () {
res.write( 'Doing ' + count.toString() + '\n' );
count--;
if ( count === 0 ) {
res.end( 'Finished\n' );
clearInterval( io );
}
}, 1000 );
} ).listen( 8000 );
The problem is here request.on('data',. request refers to the browser request.
You cannot use streaming with .exec(), because the callback function of exec is called with the rows as parameters.
To use streaming, use the .execute() method, which passes a resultset to the callback function.
I never used hdb, so I cannot give the code to use.
I've set up a NodeJS server which can be accessed by a client. Every once in a while it's necessary to let the server connect to a second server and feed the information retrieved back to the client.
Connecting to the second server is the easy part, but to be honest I have no idea how to send it back to the client. res.write seems to be forbidden during the connection with the second server.
The connection from the client is handled by handleGetRequest. The connection with the second server starts at http.get.
var http = require('http');
var url = require('url');
var server = http.createServer(function(req, res) {
var url_parsed = url.parse(req.url, true);
if (req.method ==='GET') {
handleGetRequest(res, url_parsed);
} else {
res.end('Method not supported');
}
});
handleGetRequest = function(res, url_parsed) {
if (url_parsed.path == '/secondary') {
var OPTIONS = {
hostname: "localhost",
port: "8900",
path: "/from_primary"
}
http.get(OPTIONS, function(secget) {
resget.on('data', function(chunk) {
// either store 'chunk' for later use or send directly
});
}).on('error', function(e) {
console.log("Error " + e.message);
});
} else {
res.writeHead(404);
}
res.end('Closed');
};
server.listen(8000);
How do I send the chunk from http.request to the client?
I thinks passing the callback to the handleGetRequest will fix this issue:
if (req.method === 'GET') {
handleGetRequest(url_parsed, function (err, response) {
if (err) {
return res.sendStatus(500);
}
res.json(response);
});
} else {
res.end('Method not supported');
}
handleGetRequest = function (url_parsed, callback) {
// OPTIONS ...
http.get(OPTIONS, function(resget) {
var data = '';
resget.on('data', function(chunk) {
data += chunk;
});
resget.on('end', function() {
callback(null, data);
});
}).on('error', function(e) {
callback(e);
});
}
Thanks to #TalgatMedetbekov for the suggestions. I managed to implement it like this:
var http = require('http');
var url = require('url');
var server = http.createServer(function(req, res) {
var url_parsed = url.parse(req.url, true);
if (req.method ==='GET') {
handleGetRequest(res, url_parsed);
} else {
res.end('Method not supported');
}
});
handleGetSecondaryRequest = function(callback, res) {
var OPTIONS = {
hostname: "localhost",
port: "8900",
path: "/from_primary"
}
var data = null;
http.get(OPTIONS, function(func, data) {
func.on('data', function(chunk) {
data += chunk;
});
func.on('end', function() {
callback(res, data);
});
}).on('error', function(e) {
callback(res, e);
})
};
var secReqCallback = function(res, recData)
{
res.write(recData);
res.end("END");
};
handleGetRequest = function(res, url_parsed) {
if (url_parsed.path == '/secondary') {
handleGetSecondaryRequest(secReqCallback, res);
} else {
res.writeHead(404);
}
};
server.listen(8000);
It works, kind of. There's an 'undefined' in front of the string which I can't find the cause for, but the basic functionality works perfect.
The callback construction is necessary to synchronize the asynchronous nature of NodeJS.
I'm beginning with NodeJs and I'm facing a problem I'm sure a lot of people may already have solved.
I have a basic NodeJs web server that serves files if a file is found, or 404:
var http = require('http'),
url = require('url'),
fs = require('fs'),
mongoose = require('mongoose'),
fileSystem = require('fs'),
path = require('path'),
util = require('util'),
EventEmitter = require('events').EventEmitter;
var mimeTypes = {
"html": "text/html",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"js": "text/javascript",
"css": "text/css"};
var server;
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
var personneSchema = new Schema({
nom: String,
prenom: String
});
var Personne = db.model('Personne', personneSchema);
var personneAdresseSchema = new Schema({
idPersonne: String,
idAdresse: String
});
var PersonneAdresse = db.model('PersonneAdresse', personneAdresseSchema);
var adresseSchema = new Schema({
ligne1: String,
ligne2: String,
codePostal: String,
ville: String
});
var Adresse = db.model('Adresse', adresseSchema);
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
server = http.createServer(function (request, response) {
if (request.url=='/persons') {
console.log('> Persons request');
/* IMPLEMENTATION PROBLEM HERE */
var retour='[]';
retour=retour.substr(0, retour.length-1)+']';
response.writeHead(200, {
'Cache-Control': 'no-cache, must-revalidate',
'Expires': 'Mon, 26 Jul 1997 05:00:00 GMT',
'Content-type': 'application/json'
});
response.end(retour);
console.log('> end of main function');
return;
}
var uri = url.parse(request.url).pathname;
var filename = path.join(process.cwd(), uri);
console.log("> " + filename);
fs.exists(filename, function(exists) {
if ((!exists) || (fs.lstatSync(filename).isDirectory())) {
console.log(">> fichier inexistant : " + filename);
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('404 Not Found\n');
response.end();
// Stopper tout traitement :
return;
}
var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
response.writeHead(200, {'Content-Type':mimeType});
var fileStream = fs.createReadStream(filename);
fileStream.pipe(response);
});
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
});
The problem is: the Webserver needs to get a response ready to be sent before the end of the "main" function. But if you try to do a mongoose call, it's not synchronous. If you put the following code in the main function:
Personne.find({}).select('nom prenom').exec(function (err, p) {
console.log('> Persons request finished');
});
The log shows something like:
> Persons request
> end of main function
> Persons request finished
So the main function that needs "response" to be filled can't have it filled with Personne.find({}) because Personne.find({}) finished after. What is the way to handle this? I cant find a very simple, self explaining example on the Web (nodejs + mongoose always gives me solutions with either nodejs alone, mongoose alone, or using full Web frameworks, whereas I just need a simple working example).
Any code that you want to be executed after the database call has finished has to be in the callback function for the database call. So you can't just put the database call in your main function -- you have to move all of the code from your main function that needs to be executed after the database call into the callback function instead.
If you want the server to start after your mongo query finishes, you can either use a callback:
db.once('open', function () {
server = http.createServer(function (request, response) {
Personne.find({}).select('nom prenom').exec(function (err, persons) {
// Log the result of the query
console.log(persons)
// After the query is executed, you can use the results anywhere else inside your logic
if (request.url=='/persons') {
console.log('> Persons request');
/* IMPLEMENTATION PROBLEM HERE */
var retour='[]';
retour=retour.substr(0, retour.length-1)+']';
response.writeHead(200, {
'Cache-Control': 'no-cache, must-revalidate',
'Expires': 'Mon, 26 Jul 1997 05:00:00 GMT',
'Content-type': 'application/json'
});
response.end(retour);
console.log('> end of main function');
return;
}
var uri = url.parse(request.url).pathname;
var filename = path.join(process.cwd(), uri);
console.log("> " + filename);
fs.exists(filename, function(exists) {
if ((!exists) || (fs.lstatSync(filename).isDirectory())) {
console.log(">> fichier inexistant : " + filename);
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('404 Not Found\n');
response.end();
// Stopper tout traitement :
return;
}
var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
response.writeHead(200, {'Content-Type':mimeType});
var fileStream = fs.createReadStream(filename);
fileStream.pipe(response);
});
});
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
});
I have my express code::
var express=require('express');
var fs=require('fs');
var http=require('http');
var crypto=require('crypto');
var mysql=require('mysql');
var async=require('async');
var app=express();
var connection=mysql.createConnection({
host: 'localhost',
user: '************',
password: '************',
database: 'ImagePostingDB'
});
connection.connect(function(err) {
if ( !err ) {
console.log("Connected to MySQL");
} else if ( err )
{
console.log(err);
} });
app.set('port',process.env.PORT||7004);
app.use('/Details',express.static(__dirname+'/public/images'));
app.use(express.bodyParser());
app.get('/DescriptionSortedPrice/',function(request,response){
connection.query('SELECT * FROM ImagePostingtable ORDER BY Sl_no', function(err, rows, fields) {
if (err) {
return response.send(500, err.message);
}
console.log('Found results:', rows);
response.json({
'restaurants' : rows
});
});
});
app.post('/Details/',function(req,res,next) {
var file_name=req.files.key.originalFilename;
var file_name1=req.body.key1;
var name;
console.log(file_name);
console.log(file_name1);
async.series( [
// Get the first table contents
function ( callback ) {
crypto.randomBytes(8, function(ex, buf) {
var array = req.files.key.originalFilename.split('.');
var type = array[array.length - 1];
name = buf.toString('hex') + '.' + type;
fs.rename(req.files.key.path, './public/images/' + name, function(e) {
if (e) {
res.send(500, e.message);
} else {
res.send("I got the message - This i confirm");
}
return callback(null);
});
});
},
// Updating the database
function ( callback ) {
connection.query('INSERT INTO ImagePostingtable (Image_Name,Person_Name) VALUES (?,?)', [name,file_name1], function (err, rows, fields) {
console.log('Connection result error ' + err);
return callback(null);
});
}
]);
});
app.get('/Details/',function(req,res){
res.send("Image displayed");
});
http.createServer(app).listen(app.get('port'),function(){
console.log('Express server listening on port'+app.get('port'));
});
Snapshot shows i am connected to mysql and to server
I already have few images as shown in the snapshot below in the location /public/images
Now if i test in my browser for one of the images
http://54.218.73.244:7004/c92beeaf5ba50e65.jpg
i get error as below and image is not displayed in browser
Cannot GET /c92beeaf5ba50e65.jpg
HOW TO RESOLVE THIS ! ! !
Hoping this might help someone
With the help of Andrew in one of the answers i resolved this
I just changed the line of code to below::
app.use(express.static(__dirname+'/public/images'));