Simple server on node js - javascript

Hello all :) My problem is that is not working response.vrite ()
Why ?
And another question. Will be called db.open each boot / upgrade page?
var http = require("http");
var Db = require ("mongodb").Db;
var Server = require("mongodb").Server;
function start () {
'use strict';
function onRequest (request, response) {
'use strict';
var db = new Db ("TestApp", new Server ("127.0.0.1", 27017, {}));
response.writeHead(200, {"Content-Type": "application/json", "Access-Control-Allow-Origin": "*"});
db.open (function (err, db, response) {
db.collection ('ObjectCollection', function (err, collection) {
collection.find().toArray (function (err, docs) {
console.log (docs);
response.write(JSON.stringify(docs));
});
});
});
response.end();
}
http.createServer(onRequest).listen(8080);
console.log ('Server has started...')
}exports.start = start;

You're calling response.end before your response.write. Move the response.end call inside the callbacks like this:
var http = require("http");
var Db = require ("mongodb").Db;
var Server = require("mongodb").Server;
function start () {
'use strict';
function onRequest (request, response) {
'use strict';
var db = new Db ("TestApp", new Server ("127.0.0.1", 27017, {}));
response.writeHead(200, {"Content-Type": "application/json", "Access-Control-Allow-Origin": "*"});
db.open (function (err, db, response) {
db.collection ('ObjectCollection', function (err, collection) {
collection.find().toArray (function (err, docs) {
console.log (docs);
response.write(JSON.stringify(docs));
response.end();
});
});
});
}
http.createServer(onRequest).listen(8080);
console.log ('Server has started...')
}
exports.start = start;
And yes, a new Db object will be opened on each request so it would be better to open that once during startup.

Like Johnny said, your calling response.end() outside of your asynchronous functionality. As a rule, you should never count on callbacks actually executing in a blocking manner unless you KNOW how their parent function works under the hood. DB.open likely runs that callback upon connection completion, and we don't know how long that will take. Since DB.Open is non-blocking, node then executes the response.end before DB.open's asynchronous call to the database likely even completes. You may want to read up a bit on asynchronous javascript

Related

Node express references error response is not defined

var _expressPackage = require("express");
var _bodyParserPackage = require("body-parser");
var _sqlPackage = require("mssql");
//Initilize app with express web framework
var app = _expressPackage();
//To parse result in json format
app.use(_bodyParserPackage.json());
***//Here we will enable CORS, so that we can access api on cross domain.***
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, contentType,Content-
Type,
Accept, Authorization");
next();
});
***//Lets set up our local server now.***
var server = app.listen(process.env.PORT || 4000, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
***//Set up your sql connection string, i am using here my own, you have to replace it with your
own.***
var dbConfig = {
user: "sa1",
password: "12345",
server: "localhost",
database: "test123"
};
***//Function to connect to database and execute query***
var QueryToExecuteInDatabase = function (response, strQuery) {
***//close sql connection before creating an connection otherwise you will get an error if
connection already exists.***
_sqlPackage.close();
//Now connect your sql connection
_sqlPackage.connect(dbConfig, function (error) {
if (error) {
console.log("Error while connecting to database :- " + error);
response.send(error);
}
else {
***//let's create a request for sql object***
var request = new _sqlPackage.Request();
//Query to run in our database
request.query(strQuery, function (error, responseResult) {
if (error) {
console.log("Error while connecting to database:- " + error);
response.send(error);
}
else {
response.send(responseResult);
}
});
}
});
}
***//GET API***
app.get("/StudentList", function(_req ,_res){
var Sqlquery = "select * from student1"; ***//tbl_studentdetails***
QueryToExecuteInDatabase(_res, Sqlquery);
});
***//call a stored procedure***
var request = new _sqlPackage.Request();
***//calling a stored procedure***
request.input('Username', _sqlPackage.VarChar(50), 'admin');
request.input('Password', _sqlPackage.VarChar(50), 'admin#123');
request.execute('sp_CheckLogin', function (err, recordsets, returnValue) {
response.send(recordsets);
});
> (D:\performalytic\9999.practice\angularpra\NodeApiWithSql\node_modules\mssql\lib\tedious\request.js:701:23)
at processImmediate (internal/timers.js:463:21)
- end snippet -->
This question could use a bit more clarity... but with the limited information provided it appears the issue you are running into here has to do with lexical scope.
Lexical scope most simply has to do with what variables the current execution context has access to. Inside of a function, you can either access variables declared within the function... or in the surrounding code. The last line of your code snipped shows a top level variable request and a method on that object called execute.
The callback you are passing the execute method has three variables (function parameters) you're naming err, recordsets, and returnValue. Yet inside that function body you're attempting to access a variable named response. If we look in the surrounding code... there is no response variable declared. (The only variable named response I see is within the QueryToExecuteInDatabase, and therefore only accessible within that function body.
Where are you getting this templated code from?

How to save data from JSON to a variable in NodeJS

I'm new in Node.js, I have a problem.
I would like to save data from JSON object which I have downloaded from github API.
var http = require("http");
var express = require('express');
var app = express();
var github = require('octonode');
var client = github.client();
app.set('port', process.env.PORT || 8000);
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
app.get('/getUsers', function (req, response) {
response.writeHead(200, {'Content-Type': 'text/json'});
var result;
client.get('/users/angular/repos', {}, function (err, status, body, headers) {
result = response.write(JSON.stringify(body));
console.log(result); //JSON object
return result;
});
console.log(result); //undefined
});
How can I save an data from object to single variable?
(I want to then transform it to an Array and take some useful data).
You will not get result outside of the asynchronous call as it is not yet defined. To get this value either call a method inside the callback of query or use async module and pass it.
app.get('/getUsers', function (req, response) {
response.writeHead(200, {'Content-Type': 'text/json'});
var result;
client.get('/users/angular/repos', {}, function (err, status, body, headers) {
result = response.write(JSON.stringify(body));
console.log(result); //JSON object
doSomeOperationOnResult(result)
});
});
function doSomeOperationOnResult(result){
//Your operating code
}

how to run different .js file in one server.js file in NODE JS?

this is demo.js file and i want to use this file in server.js file so that i can use diffrent js files in one server file.
Demo.js:
app.get('/add User', function (req, res) {
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/project';
MongoClient.connect(url, function (err, db) {
var collection = db.collection('users');
collection.find({name: 'shruti'}).toArray(function (err, result) {
console.log(, result);
db.close();
});
Server.js:
var a = require('./demo.js');
vr http=require("http");
var server = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.write(a);
res.end();});
server.listen(7860);
A possible sample would look like :
demo.js
var myModule = {
defineRoutes: function(router){
//do something...
}
}
module.exports = myModule;
server.js
var myModule = require('demo.js');
myModule.defineRoutes(router);
As stated, you need to export.
When you do:
var item = require("mymodule");
Require returns an object, which is a reference the value of module.exports for that given file - in your case demo.js.
You can write your modules a few ways as some people have shown you. Because it is encapsulated you basically are identifying what is public or can be called. Few ways to write it - you could also do:
module.exports = {
yourCall: function () {
console.log("stuff here");
}
};
As stated by #ishann, who is dead on here, you are writing something you assume might be populated. Going to a database and returning is an asynchronous call - so it will take time to go do that and then for the results to be returned.
Based on your structure - ideally what you want to do is assign the route ( "/addUser" ) which will pass in the response object to you:
app.get('/add User', function (req, res) {
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/project';
MongoClient.connect(url, function (err, db) {
var collection = db.collection('users');
collection.find({name: 'shruti'}).toArray(function (err, result) {
console.log(, result);
db.close();
// set the type
res.writeHead(200, {"Content-Type": "application/json"});
res.write(result);
});
Just looks like your code needs a bit of reorg, but separting concerns is good. You might want to also check out Express as a framework for node.

How to add a callback in this function for gzip

Here is my code:
/*jshint globalstrict: true*/
var zlib = require('zlib');
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html', 'Content-Encoding': 'gzip'});
var text = "Hey this works!";
zlib.gzip(text, function (_, result) {
res.end(result);
});
}).listen(8081);
I want to add a callback to the above code to follow the node.js async concept. How do I do that? Also, I am pretty new to node.js
var callback = function (err, result) {
// gzip has finished, do any thing you want here,
// also add if about the 'err' as mscdex said.
res.end(result);
}
zlib.gzip(text, callback);
callback is a function,you already added it .

Node.js wait for callback of REST service that makes HTTP request

I am using the express module to build a RESTful API within Node.js. In my service I am making additional HTTP requests to external endpoints (server side). I need to return the data from those HTTP requests to the request body of my Web service.
On all the actions the Web service is conducting, by using console.log() I have confirmed that I get the data I need. However, when I try to return those values to the service they come back with value null. I know this is because a request is asynchronous and the callback is not waiting for the HTTP request to finish.
Is there a way to make this work?
A common practice is to use the async module.
npm install async
The async module has primitives to handle various forms of asynchronous events.
In your case, the async#parallel call will allow you to make requests to all external APIs at the same time and then combine the results for return to the requester.
Since you're making external http requests, you will probably find the request module helpful as well.
npm install request
Using request and async#parallel your route handler would look something like this...
var request = require('request');
var async = require('async');
exports.handler = function(req, res) {
async.parallel([
/*
* First external endpoint
*/
function(callback) {
var url = "http://external1.com/api/some_endpoint";
request(url, function(err, response, body) {
// JSON body
if(err) { console.log(err); callback(true); return; }
obj = JSON.parse(body);
callback(false, obj);
});
},
/*
* Second external endpoint
*/
function(callback) {
var url = "http://external2.com/api/some_endpoint";
request(url, function(err, response, body) {
// JSON body
if(err) { console.log(err); callback(true); return; }
obj = JSON.parse(body);
callback(false, obj);
});
},
],
/*
* Collate results
*/
function(err, results) {
if(err) { console.log(err); res.send(500,"Server Error"); return; }
res.send({api1:results[0], api2:results[1]});
}
);
};
You can also read about other callback sequencing methods here.
Node.js is all about callbacks. Unless the API call is synchronous (rare and shouldn't be done) you never return values from those calls, but callback with the result from within the callback method, or call the express method res.send
A great library for invoking web requests is request.js
Let's take the really simple example of calling google. Using res.send, your express.js code could look like:
var request = require('request');
app.get('/callGoogle', function(req, res){
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
// from within the callback, write data to response, essentially returning it.
res.send(body);
}
})
});
Alternatively, you can pass a callback to the method that invokes the web request, and invoke that callback from within that method:
app.get('/callGoogle', function(req, res){
invokeAndProcessGoogleResponse(function(err, result){
if(err){
res.send(500, { error: 'something blew up' });
} else {
res.send(result);
}
});
});
var invokeAndProcessGoogleResponse = function(callback){
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
status = "succeeded";
callback(null, {status : status});
} else {
callback(error);
}
})
}
Wait.for
https://github.com/luciotato/waitfor
Other answer's examples using wait.for:
Example from from Daniel's Answer (async), but using Wait.for
var request = require('request');
var wait = require('wait.for');
exports.handler = function(req, res) {
try {
//execute parallel, 2 endpoints, wait for results
var result = wait.parallel.map(["http://external1.com/api/some_endpoint"
,"http://external2.com/api/some_endpoint"]
, request.standardGetJSON);
//return result
res.send(result);
}
catch(err){
console.log(err);
res.end(500,"Server Error")
}
};
//wait.for requires standard callbacks(err,data)
//standardized request.get:
request.standardGetJSON = function ( options, callback) {
request.get(options,
function (error, response, body) {
//standardized callback
var data;
if (!error) data={ response: response, obj:JSON.parse(body)};
callback(error,data);
});
}

Categories