I have recently started using Node.js and jQuery and I can't figure out what's wrong in my project.
I have a client application that sends a post request to a node js server; this server gets the datas from the post and performs a query; finally it should send back to the client a json containing the informations retrieved from the previous query. The problem is that the response sent by node js is an empty object( {} ) and I don't know why.
Here my source code:
Node JS:
var http = require("http");
var url = require('url');
var querystring = require('querystring');
var express = require('express');
var cookieParser = require('cookie-parser');
var mysql = require('mysql');
var con = mysql.createConnection({
host: "",
user: "",
password: "",
database : ''
});
var app = express();
app.use(express.static(__dirname + '/public'))
.use(cookieParser());
app.post('/search',function(req, res) {
if (req.method == 'POST') { //PUT Only
var body = '';
req.on('data', function (data){body += data;});
req.on('end', function () {
var post = querystring.parse(body);
console.log("Dati in ingresso > " + JSON.stringify(post));
//res.writeHead(200, {'Content-Type': 'text/plain'})
query("SELECT Nome FROM Mood WHERE Nome LIKE \'" + post.data + "%\'",res);
});
}else{
console.log("Not POST request")
res.end();
}
});
var query = function(q,res) {
var results = {};
con.query(q, function (err, result, fields) {
if (err) throw err;
results = JSON.stringify(JSON.parse(JSON.stringify(result))[0].Nome);
console.log("Risultati query: ");
console.log(results);
});
res.json(results);
res.end();
}
app.listen(8888);
Client:
$("document").ready(function () {
$('#search-box').on('input propertychange', function(e){
var input = $(this).val();
var array = ['prova1','prova2','prova3'];
var ul = $('#results-options ul');
$.ajax({
type: "POST",
url: "/search",
data: {data : input},
contentType: "application/json",
success: function(d) {
console.log(d);
console.log(JSON.stringify(d));
console.log(JSON.parse(d));
},
error: function(d) {
console.log("Error");
}
});
$('#results-options').show();
});
$("#results-options").on('click',function (e) {
$('this').show();
e.stopPropagation();
})
$(document).on('click', function(){
$('#results-options').hide();
})
});
As I stated above, your query function is sending back a response before the query to the database has finished. That's why it is coming back empty. I moved the res.json(results); res.end(); code inside the callback of the DB query.
var query = function(q,res) {
var results = {};
con.query(q, function (err, result, fields) {
if (err) throw err;
results = JSON.stringify(JSON.parse(JSON.stringify(result))[0].Nome);
console.log("Risultati query: ");
console.log(results);
// I moved the code here
res.json(results);
res.end();
});
// Your old code
// res.json(results);
// res.end();
};
Related
I have the following code:
serverside.js:
var express = require('express');
var app = express();
app.post('/LEDon', function(req, res) {
var obj = res;
console.log('LEDon button pressed!');
// Run your LED toggling code here
});
app.listen(1337);
clientside.js:
$('#ledon-button').click(function() {
var test = "123";
$.ajax({
type: 'POST',
url: 'http://localhost:1337/LEDon',
data: JSON.stringify(test),
contentType: 'application/json'
});
});
view.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button id='ledon-button'>LED on</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src='clientside.js'>
</script>
</body>
</html>
Nothing happens when I click the button. But if I remove some lines from clientside.js it works:
$('#ledon-button').click(function() {
var test = "123";
$.ajax({
type: 'POST',
url: 'http://localhost:1337/LEDon',
});
});
But this way no JSON-file is being sent. I tried looking at tutorials but found nothing. What am I missing?
So this is how I solved it:
clientside:
function getData(number) {
var teamId = number; // in data!!
$.ajax({
type: "POST",
url: "http://localhost:80/getdata",
crossDomain:true,
dataType: "json",
data:JSON.stringify(teamId)
}).done(function ( data ) {
var myJSON = JSON.stringify(data);
}
server side:
var express = require('express');
var app = express();
// Load the http module to create an http server.
var http = require('http');
const mysql = require('mysql');
app.post('/getdata', function(request, response) {
var store = '';
var query;
var query2;
// First you need to create a connection to the db
const con = mysql.createConnection({
host: 'db.host.net',
user: 'dbuser',
password: 'mypw',
database: 'dbname',
});
request.on('data', function(data) {
store += data;
query = "regular db query";
con.connect((err) => {
if (err) {
console.log('Error connecting to Db');
return;
}
console.log('Connection was established');
});
con.query(query, (err, rows) => {
if (err) throw err;
// handling query stuff
query2 = "regular db query";
// getting db query
con.query(query2, (err, rows2) => {
// handling query stuff
if (err) throw err;
myJSON = {
"var1": "data1",
"va2": "data2"
}
console.log("\nThe JSON resultset: " + JSON.stringify(myJSON));
response.end(JSON.stringify(myJSON));
con.end();
});
});
console.log("DB connection ended");
});
request.on('end', function() {
response.setHeader("Content-Type", "text/json");
response.setHeader("Access-Control-Allow-Origin", "*");
});
}); app.listen(80);
Let me know if something is unclear or can be done better.
i have a little problem here, i want to make simple chat app using nodejs, but in terminal this error was come out, of course in web browser chat app doesn't work, this is my code
// # SimpleServer
//
// A simple chat server using Socket.IO, Express, and Async.
//
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
//set this to your project URL
var c9server = 'http://sne.dlinkddns.com:8080/politan/writeData.php';
//ssl issues in c9
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
//
// ## SimpleServer `SimpleServer(obj)`
//
// Creates a new instance of SimpleServer with the following options:
// * `port` - The HTTP port to listen on. If `process.env.PORT` is set, _it overrides this value_.
//
var router = express();
var server = http.createServer(router);
var io = socketio.listen(server);
router.use(express.static(path.resolve(__dirname, 'client')));
var messages = [];
var sockets = [];
// create connection to file
// var fs = require('fs');
// var writeStream = fs.createWriteStream('log.json');
io.on('connection', function (socket) {
messages.forEach(function (data) {
socket.emit('message', data);
});
sockets.push(socket);
socket.on('disconnect', function () {
sockets.splice(sockets.indexOf(socket), 1);
updateRoster();
});
socket.on('message', function (msg) {
var text = String(msg || '');
if (!text)
return;
var d = new Date();
socket.get('name', function (err, name) {
var data = {
name: name,
text: text,
date: d
};
var trendData = {
date: d,
count: '1'
};
broadcast('message', data);
messages.push(data);
//log data
logData(data, 'messages.json');
logData(trendData, 'trend.json');
//write data to mysql
postData('data='+JSON.stringify(data), c9server);
});
});
socket.on('identify', function (name) {
socket.set('name', String(name || 'Anonymous'), function (err) {
updateRoster();
});
});
});
function updateRoster() {
async.map(
sockets,
function (socket, callback) {
socket.get('name', callback);
},
function (err, names) {
broadcast('roster', names);
}
);
}
function broadcast(event, data) {
sockets.forEach(function (socket) {
socket.emit(event, data);
});
}
function logData(data, file){
//setup file
var fs = require('fs');
//append the new data to the log
fs.appendFile(file, JSON.stringify(data)+"\n", function (err) {
if (err) throw err;
console.log(JSON.stringify(data) +' was appended to file!');
});
}
function postData(data, postUrl){
var request = require('request');
// Set the headers
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
}
// Configure the request
var options = {
url: postUrl,
method: 'POST',
headers: headers,
form: data
}
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
console.log(body)
} else {
console.log(error);
}
})
}
// server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
server.listen(8081, process.env.IP, function(){
var addr = server.address();
console.log("Chat server listening at", addr.address + ":" + addr.port);
});
The error in console
Missing error handler on `socket`.
TypeError: undefined is not a function
at Socket.<anonymous> (/var/www/html/politan/server.js:89:14)
at Socket.emit (events.js:107:17)
at Socket.onevent (/var/www/html/politan/node_modules/socket.io/lib/socket.js:335:8)
at Socket.onpacket (/var/www/html/politan/node_modules/socket.io/lib/socket.js:295:12)
at Client.ondecoded (/var/www/html/politan/node_modules/socket.io/lib/client.js:193:14)
at Decoder.Emitter.emit (/var/www/html/politan/node_modules/component-emitter/index.js:134:20)
at Decoder.add (/var/www/html/politan/node_modules/socket.io-parser/index.js:247:12)
at Client.ondata (/var/www/html/politan/node_modules/socket.io/lib/client.js:175:18)
at Socket.emit (events.js:107:17)
at Socket.onPacket (/var/www/html/politan/node_modules/engine.io/lib/socket.js:101:14)
Glad if you can help my little project, thanks
I've wrote this service using node, it works but i don't know how to call it from an angularjs controller, i nedd to call the post method
this is the service:
var app = require('express')();
var http = require('http').Server(app);
var mysql = require('mysql');
var bodyParser = require("body-parser");
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'repositorio',
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/',function(req,res){
var data = {
"error":1,
"Usuarios":""
};
connection.query("SELECT * from usuario",function(err, rows, fields){
if(rows.length != 0){
data["error"] = 0;
data["Usuarios"] = rows;
res.json(data);
}else{
data["Usuarios"] = 'Usuarios no encontrados..';
res.json(data);
}
});
/*var data = {
"Data":""
};
data["Data"] = "Welcome to Book Store DEMO...";
res.json(data);*/
});
app.post('/usuario',function(req,res){
var Email = req.query.correo;
var Password = req.query.contrasena;
var Nombres = req.query.nombres;
var Apellidos = req.query.apellidos;
var Usuario = req.query.usuario;
var data = {
"error":1,
"Usuario":""
};
console.log("Email: "+Email+" Password "+Password+" Nombres "+Nombres+" Apellidos "+Apellidos+" Usuario"+Usuario);
if(!!Email && !!Password && !!Nombres && !!Apellidos && !!Usuario){
var user ={usu_correo: Email,usu_contrasena: Password,usu_nombres:Nombres,usu_apellidos: Apellidos,usu_usuario:Usuario}
connection.query('INSERT INTO usuario SET ?',user,function(err, rows, fields){
if(!!err){
data["Usuario"] = "Error Adding data";
}else{
data["error"] = 0;
data["Usuario"] = "Usuario adicionado con éxito";
}
res.json(data);
});
}else{
data["Usuario"] = "Please provide all required data";
res.json(data);
}
});
http.listen(8080,function(){
console.log("Connected & Listen to port 8080");
});
and this is me trying to connect it with angular, i need help please
var app = angular.module('el_acorde_web', []);
app.controller('usuarioscontroller', function($scope, $http)
{
$scope.usuario = {};
$scope.usuario.correo = "davidstl5#gmail.com";
$scope.usuario.nombres = "David Fernano";
$scope.usuario.apellidos = "Sotelo";
$scope.usuario.contrasena = "lakjsdlfkja";
$scope.usuario.usuario = "davidstl5";
$scope.registrar = function(){
$http.post('http://localhost:8080/usuario', $scope.usuario)
.success(function(data)
{
alert(data);
})
.error(function(data)
{
alert('Error:' + data);
});
}
});
Your code looks fine, can I see the HTML code where you are calling the registrar function? Looks like you only have to add the ng-click directive if everything else is working, and for a best practice I would create a factory or a service and call a function there that interacts with the Node app.
I found the solution!
Chrome is the problem we install https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en
and then use:
$scope.registrar = function(){
alert("Entre");
/*$http.post('http://localhost:8080/usuario', $scope.usuario)
.success(function(data)
{
alert(data);
})
.error(function(data)
{
alert('Error:' + data);
});*/
var datos = {correo: $scope.usuario.correo, contrasena: $scope.usuario.contrasena,
nombres:$scope.usuario.nombres, apellidos: $scope.usuario.apellidos,
usuario: $scope.usuario.usuario};
var request = $http({
method: "POST",
url: "http://localhost:8080/usuario",
data: datos,
headers: { 'Content-Type': 'multipart/form-data', 'Authorization': 'Basic ' + btoa(datos),
'Access-Control-Allow-Origin': "*"}
});
request.success(
function( data ) {
alert(data);
}
);
request.error(
function( data ) {
alert(data);
}
);
}
and everything works!
I just started working with Nodejs.
I am using Restify to get data from: http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo'.
My code below gives me an error: {"code":"ResourceNotFound","message":"/ does not exist"}
var restify =require("restify");
var server = restify.createServer();
server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.get('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo', function (req, res) {
console.log(req.body);
res.send(200,req.body);
});
server.listen(7000, function () {
console.log('listening at 7000');
});
That's because Restify is for creating REST endpoints, not consuming them. You should check out this SO post for help consuming data from an API.
e.g. create test.js with the following:
var http = require('http');
var options = {
host: 'api.geonames.org',
path: '/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo'
};
var req = http.get(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
// Buffer the body entirely for processing as a whole.
var bodyChunks = [];
res.on('data', function(chunk) {
// You can process streamed parts here...
bodyChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(bodyChunks);
console.log('BODY: ' + body);
// ...and/or process the entire body here.
})
});
req.on('error', function(e) {
console.log('ERROR: ' + e.message);
});
then run node test.js.
I found what I was looking for. You can use restify client to get JSON data:
Here is my solution:
var restify = require("restify");
function getJSONDataFromUrl(){
var query = "?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo";
var options = {};
options.url = "http://api.geonames.org";
options.type = options.type || "json";
options.path = "/citiesJSON" + query;
options.headers = {Accept: "application/json"};
var client = restify.createClient(options);
client.get(options, function(err, req, res, data) {
if (err) {
console.log(err);
return;
}
client.close();
console.log(JSON.stringify(data));
return JSON.stringify(data);
});
}
getJSONDataFromUrl();
I want to send form data to node.js server using Ajax and I am fallowing the below approach to send data.
I am not getting how receive it in node.js server program I am not using express framework for node.js
client.HTML
<script>
function myFunction() {
var region = document.getElementById("region").value;
var os = document.getElementById("os").value;
var data = {};
data.region = region;
data.os = os;
$.ajax({
type: 'post',
datatype: 'jsonp',
data: JSON.stringify(data),
contentType: 'application/json',
url: 'http://127.0.0.1:8083/', //node.js server is running
success: function(data) {
alert("success");
}
});
</script>
<form>
<select id="region" name="region" class="region"></select>
<select id="os" name="os" class="os"></select>
<input type="button" value="search" class="fil_search" onclick="myFunction()"/>
</form>
server.js
var http = require('http');
var fs = require('fs');
var url = require('url');
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert')
var ObjectId = require('mongodb').ObjectID;
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var result1=[];
var result2=[];
var result3=[];
var result4=[];
var result5=[];
var result6=[];
var result7=[];
var i=0;
var region;
var os;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect("mongodb://192.168.1.22:27017/test", function(err, db) {
if(err) { return console.dir(err); }
else {
app.get('/',function(req, res) {
var url_parts = url.parse(req.url, true);
var url_parsed = url.parse(req.url, true);
"i want data here from ajax to perform"
console.log("connected");
var instance = db.collection('instance');
var region = db.collection('region');
region.findOne(({$and: [{"region_name": region_name},{"os_type": os}]}), function(err, result){
if(err){
throw(err);
}
else{
console.log(region);
var newr = result.inst_name;
instance.find({ "inst_id": { "$in": newr } }).toArray(function(err, resultn){
if(err){
throw(err);
}
else{
var len=resultn.length;
console.log(resultn);
console.log(len);
for(var i=0;i<len;i++)
{
result1[i]=resultn[i].inst_type;
result2[i]=resultn[i].vcpu;
result3[i]=resultn[i].memory_gib;
result4[i]=resultn[i].storage;
result5[i]=resultn[i].phy_processor;
result6[i]=resultn[i].clock_spd;
result7[i]=resultn[i].netwk_pef;
}
var wstream = fs.createWriteStream('myOutput.txt');
wstream.write(result1.toString()+"~"+result2.toString());
//var str = "Hi man"
res.writeHead(200, {'Content-Type':'text/html'});
//res.end(url_parsed.query.callback+'("'+resultn.toString()+'")');
res.end(url_parsed.query.callback+'("'+result1.toString()+"~"+result2.toString()+"~"
+result3.toString()+"~"+result4.toString()+"~"+result5.toString()+"~"+result6.toString()
+"~"+result7.toString()+'")');
}
});
}
});
}).listen(process.env.PORT || 8083);
}
});
I am not getting how to receive data in node.js server program and after receiving data I want process on that data and send back processed data to same HTML page.
If you have app.use(bodyParser.urlencoded({ extended: true })); in your server.js file then using bodyParser you can retrieve data from ajax as given below:
app.post('/', function(req, res) { //your ajax should also post to url: '/'
var region = req.body.region,
os = req.body.os;
// ...
});