Value not updating in PostgreSQL using NodeJs - javascript

var express = require('express');
var app = express();
var pg = require('pg');
var connectionString = "postgresql://postgres:sujay123#localhost:3001/redc";
app.use(express.static('public'));
app.get('/index.html', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
app.get('/process_get', function (req, res) {
response = {
name:req.query.name,
lat:req.query.lat,
long1:req.query.long
};
console.log(response);
res.end(JSON.stringify(response));
var client = new pg.Client(connectionString);
client.connect();
console.log("connect");
console.log("INSERT INTO data(name, latitude,longitude) values('"+req.query.name+"',"+req.query.lat+","+req.query.long+")");
var i = client.query("INSERT INTO data values('"+req.query.name+"',"+req.query.lat+","+req.query.long+")");
console.log(i);
console.log("Query Inserted")
})
var server = app.listen(3001, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
I am getting this code and running but when i check the db the insert query has not worked and th values in the 3 paramters are coming of name, lat and long just the query isnt working i guess.

Yes your syntax for insert is wrong. The query that you are logging in console looks correct, but it's different from the string you're using in the database query.

Related

extract value after the endpoint and assign it to a child function in Java Script using Express

I am just 2 days old in JS, so, asking a question that may sound a basic one.
I have a server running at localhost:8000/api/namespace.
const express = require('express');
const app = express();
app.get('/', function (req, res) {
res.send('Welcome to deletion task!!!');
});
app.get('/api/namespace/:namespaceName', function (req, res) {
namespaceName = res.send(req.params);
console.log(`${namespaceName}`);
});
var server = app.listen(8000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
The output of console.log(`${namespaceName}`); is object obect
On accessing URL as http://localhost:8000/api/namespace/abcd, it is giving the output as {"namespaceName":"abcd"}.
What I am trying to achieve is to get the value "abcd" into a variable and pass it into a child process as an argument(${namespaceName}) to a shell script.
var child_process = require('child_process');
child_process.execFile('./restart.sh', [`${namespaceName}`],
function (error, stdout, stderr) {
if (error !== null) {
console.log(error);
} else {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
}
});
I am not able to achieve it.
Help, please.

Triggering socket.io real-time notifications from Express 4 middleware

I am building a real-time notification system using socket.io. This is my server-side code at the moment:
bin/www:
var app = require('../app');
var server = http.createServer(app);
var io = app.io
io.attach(server);
server.listen(port, function(err) {
if (err) console.log(err);
console.log('Listening on port ' + port + '...');
});
app.js:
var socket_io = require('socket.io');
var express = require('express');
var app = express();
var io = socket_io();
app.io = io;
require('./config/socket')(app.io);
config/socket.js:
var User = require('../controllers/user');
module.exports = function (io) {
io.on('connection', function (socket) {
console.log('Socket.io connected');
socket.emit('connection', "Connection created.");
socket.on('send notification', function(data) {
User.createNotification(socket.request.user, data);
});
});
};
routes/index.js:
var express = require('express');
var User = require('../controllers/user');
var router = express.Router();
router.post('/order', User.order);
module.exports = router;
controllers/user.js:
var User = require('../models/user').model;
var io = require('socket.io');
module.exports = {
order: function(req, res) {
/* some create order code */
io.emit('send notification', 'Your order was successful!');
res.sendStatus(200);
}
}
I keep getting the error TypeError: io.emit is not a function whenever I try to call the route POST /send even though I am clearly initiating socket.io in my app.js and bin/www files and requiring it in controllers/user.js. All the examples I've seen online emit notifications from within this part:
io.on('connection', function (socket) {
socket.emit(event, msg);
});
but I want my notifications to be triggered from the middleware so I can send custom notifications to the user when certain events happen in the application backend.
Try the following instead:
io.on('connection', function(socket){
socket.on('xxx', function(obj){
io.emit('xxx', {xxx: xxx})
})
})
This should suppress your TypeError:.

Socket.io socket emit not being called

I have this index.js file on the client:
var socket;
var init = function() {
// Setup Socket:
socket = io.connect();
// Setup Event Handlers:
setEventHandlers();
// Connect to Server:
socket.emit('connect', {
name : "User Name"
});
console.log("Client Init Complete.");
}
var setEventHandlers = function() {
// Set Routes For Connections
socket.on("connection resp", onConnected);
}
var onConnected = function(data) {
console.log(data.resp);
}
And I have this code on the server:
// SETUP:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var request = require('request');
var path = require('path');
var socket = require('socket.io')(http);
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0';
var bodyParser = require('body-parser')
var fs = require('fs');
// SETUP:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended : false
}));
app.configure(function() {
app.use(express.static(path.join(__dirname, 'public')));
})
var setEventHandlers = function() {
socket.sockets.on("connection", onInit);
};
var onInit = function(client) {
client.on("connect", onConnect);
};
var onConnect = function(data) {
console.log("Called");
}
// Send index page html
app.get('/', function(req, res) {
res.sendfile("public/html/index.html");
});
// Turn on server
http.listen(server_port, server_ip_address, function() {
console.log("App Listening on " + server_ip_address + ", server_port "
+ server_port);
});
setEventHandlers();
The issue is that on the onConnect on the server is never called. Eventhough I call socket.emit("connect") on the client.
After further testing, it seems that the socket id is undefined: this.id returns undefined.
You need to add quotes to the parameters in the socket.emit function like this:
// Connect to Server:
socket.emit('connect', {
'name' : 'User Name'
});
You should initialize your socket variable through io.connect("server address") and has i see in your code you have not passed any parameter to io.connect
.If server is in your local machine then connect to it by io.connect("http://localhost").
For more information see Docs. socket.io-client

Show database content in browser with node.js, MySQL and Jade

I'm currently working with Node.js, Express.js and Jade. My database is MySQL. I'm new to node.js, so I thought I try something very easy: Displaying some data from the database in a table in the browser.
Unfortunately it still doesn't work. I can display data on an free port but not where I need it - on port 3000. And I also can't work with the response itself. This is one of the "solutions" or ideas I had. Maybe there is a problem with the asynchronous call? I simply have no idea.
Here is my code:
routes.js
var express = require('express');
var controller = express.Router();
var dataModel2 = require('../models/rooms');
controller.get('/rooms', function(req, res, next) {
var rooms = dataModel2();
res.render('rooms', {
items: rooms
});
});
module.exports = controller;
models/rooms.js
var rooms;
var connection = require('./databaseConnection');
var http = require('http');
rooms = function() {
http.createServer(function (request, response)
{
console.log('Creating the http server');
connection.query('SELECT * FROM rooms', function(err, rows, fields)
{
response.writeHead(200, { 'Content-Type': 'application/json'});
var room = response.end(JSON.stringify(rows));
return room;
});
});
module.exports = rooms();
models/databaseConnection.js
var mysql = require('mysql');
module.exports = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'raspi_key_royal'
});
rooms.jade
extends layout
block content
div(id="bodyRoyal")
table(border='1')
thead
tr
th ID
th Name
tbody
each item in items
tr
td=item.rid
td=item.name
I splitted the functions a bit because there are some other sections like "persons" etc. I tried to insert console.logs in the rooms.js but that doesn't seem to work.
I also thought I could save the response into a variable so that I can work with it somewhere else.
Thank you for every help and hints!
Steffi
Something like this should do it:
var express = require('express'),
app = express(),
connection = require('./databaseConnection');
app.get('/rooms', function (req, res) {
connection.query('SELECT * FROM rooms', function(err, rows, fields)
{
res.render('rooms', {
items: rows
});
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
This is from the express site...http://expressjs.com/starter/hello-world.html
app.listen(3000, ...
is the how to configure a it to a specific port (in this case 3000).
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});

Setting up a MongoDB database connection with node.js

How would I set up a MongoDB database connection with node.js?
Here is my app.js file:
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000);
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.htm');
});
app.use(express.static(__dirname + '/assets'));
io.sockets.on('connection', function(socket) {
socket.on('send message', function(data) {
io.sockets.emit('new message', data);
});
});
I have already set-up MongoDB and have it running as a service on Windows.
As of 1.2, the recommended way to perform a connection is in documentation:
http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html
excerpt:
var MongoClient = require('mongodb').MongoClient
, Server = require('mongodb').Server;
var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
var db1 = mongoClient.db("mydb");
mongoClient.close();
});
You may find that a connection singleton is useful for the current state of the official node.js driver. Below is some sample code that I use:
connection.js module:
var MongoClient = require('mongodb').MongoClient;
var db_singleton = null;
var getConnection= function getConnection(callback)
{
if (db_singleton)
{
callback(null,db_singleton);
}
else
{
//placeholder: modify this-should come from a configuration source
var connURL = "mongodb://localhost:27017/test";
MongoClient.connect(connURL,function(err,db){
if(err)
log("Error creating new connection "+err);
else
{
db_singleton=db;
log("created new connection");
}
callback(err,db_singleton);
return;
});
}
}
module.exports = getConnection;
Referencing module:
var getConnection = require('yourpath/connection.js')
function yourfunction()
{
getConnection(function(err,db)
{
//your callback code
}
.
.
.
}

Categories

Resources