I have used below code. i have run the file and there are no errors. But the server 192.123.1.134:5001 shows 'No data received'.
Kindly help me to find out error in the code.
express = require('express');
app = express();
config = require('./config/database.js');
var path = require('path');
//app.set('views', __dirname + '/views')
app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'jade');
router = express.Router();
var routes = require('./user/index');
var admin = require('./user/user');
app.use('/', routes);
app.use('/user', admin);
http = require('http');
server = http.createServer(app);
server.listen('5001','192.123.1.134', function(){
console.log('%s: Node server started on %s:%d ...',Date(Date.now() ));
});
index.js
var User = require('../model/user.js');
router.get('/', function(req, res, next) {
User.getuserdetails(function(data) {
res.render('user', {
title: 'Welcome',
result : data
});
});
//res.render('index', { title: 'welcome' });
});
module.exports = router;
user.js (model)
var connection =require("../config/database.js");;
router.getuserdetails = function (req,res){
var result = connection.query('SELECT * FROM table1','', function (err, rows) {
if (err) throw err
});
}
module.exports = router;
database.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'aaa',
database : 'my_db'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
Just give the localhost/127.0.0.1 in the IP address part.
You can access it in LAN using your IP address 192.123.1.134.
server.listen('5001','127.0.0.1', function(){
console.log('%s: Node server started on %s:%d ...',Date(Date.now() ));
});
Related
I'm sure this has already been answered but I can't find the exact question I'm looking for.
I have an ejs file that has this for the form.
<form action="" method="POST">
<div class="input-group">
<input type="text" class="form-control" name="userSearchInput" placeholder="Enter the id of the product you would like to buy" aria-label="Recipient's username" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-outline-secondary" id="searchBTN" type="submit"><i class="fas fa-cart-plus mr-2"></i>Add to Cart</button>
</div>
</div>
</form>
On the node side in my app.js file, I've installed and downloaded both express and body-parser and done the requisite require function.
var bodyParser = require('body-parser');
var express = require('express');
var app = express();
I've set up my middleware for body-parser here:
// middleware for bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
Then, to get the content of what the user types into the input text box, I'm using this:
app.post('/', function(req, res) {
var item = req.body.userSearchInput;
console.log(item);
});
This is my first time using app.post and since nothing is being console logged- I'm not sure where I'm going wrong.
full app.js file
var express = require('express');
var path = require('path');
var http = require('http');
var mysql = require('mysql');
var bodyParser = require('body-parser');
var nodemon = require('nodemon');
var app = express();
var port = process.env.PORT || 3000;
// setting up views
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
// middleware for bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// create connection to mySQL db
var connection = mysql.createConnection ({
host : 'localhost',
user : 'root',
password : 'root',
database : 'bamazon'
});
// initialize connection
connection.connect();
// run db query and print items to index html home page
connection.query('SELECT * from products', function (error, results) {
if (error) throw error;
console.log(results);
app.get('/', function(req, res){
res.render('index', {list: results});
})
});
app.post('/', function(req, res) {
var item = req.body.userSearchInput;
console.log(item);
});
// setting up listen for server function
app.listen(port, function (err) {
if (err) throw err;
console.log("Server is running on port " + port);
});
use
<form action="/" method="post">
Firstly add form action in your ejs file like action="/search".Step 2: try with app.post('/search'
Works fine i just commented out db connections only.
may be try this app.js file with new express project.
Run command node app instant of npm start
var express = require('express');
var path = require('path');
var http = require('http');
var bodyParser = require('body-parser');
// var nodemon = require('nodemon');
// var mysql = require('mysql');
var app = express();
var port = process.env.PORT || 3000;
// setting up views
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
// middleware for bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
/*
create connection to mySQL db
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'bamazon'
});
// initialize connection
connection.connect();
// run db query and print items to index html home page
connection.query('SELECT * from products', function (error, results) {
if (error) throw error;
console.log(results);
});
*/
app.get('/', function (req, res) {
res.render('index', { list: [], title:"salman" });
})
app.post('/', function (req, res) {
var item = req.body.userSearchInput;
console.log(item);
});
// setting up listen for server function
app.listen(port, function (err) {
if (err) throw err;
console.log("Server is running on port " + port);
});
I want to establish https request to my api and i have written following lines of code in NodeJS function:
function getUsers() {
/**
* HOW TO Make an HTTP Call - GET
*/
// options for GET
var optionsget = {
host: 'localhost', // here only the domain name
// (no http/https !)
port: 3000,
path: '/api/users', // the rest of the url with parameters if needed
method: 'GET' // do GET
};
console.info('Options prepared:');
console.info(optionsget);
console.info('Do the GET call');
// do the GET request
var reqGet = https.request(optionsget, function (res) {
console.log('Requested');
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
res.on('data', function (d) {
console.info('GET result:\n');
process.stdout.write(d);
console.info('\n\nCall completed');
});
});
reqGet.end();
reqGet.on('error', function (e) {
console.error('Last error:' + e);
});
}
Server side code:
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 mysql = require("mysql");
var md5 = require('MD5');
var rest = require("./REST.js");
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
function REST() {
var self = this;
self.connectMysql();
}
REST.prototype.connectMysql = function () {
var self = this;
var pool = mysql.createPool({
connectionLimit: 100,
host: 'localhost',
user: 'root',
password: 'root',
database: 'oes_api',
debug: false
});
pool.getConnection(function (err, connection) {
if (err) {
self.stop(err);
} else {
self.configureExpress(connection);
}
});
};
REST.prototype.configureExpress = function (connection) {
var self = this;
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
var router = express.Router();
app.use('/api', router);
app.use('/', index);
app.use('/users', users);
var rest_router = new rest(router, connection, md5);
self.startServer();
};
REST.prototype.startServer = function () {
app.listen(3000, function () {
console.log("All right! I am alive at Port 3000.");
});
};
REST.prototype.stop = function (err) {
console.log("ISSUE WITH MYSQL \n" + err);
process.exit(1);
};
new REST();
But https connection is not establishing saying Last error:Error: socket hang up.
Could you please help me out to get ride out from this error.
It looks like you can create your server using https. Take a look at this page in the Node Documentation for doing so.
Example
const https = require('https');
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
I'm new to Node.js and Express.
How can I access the variable created in "app.js" called "pg" in "routes/index.js"?
app.js
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var pg = require('pg');
var conString = "postgres://someuser:somepass#localhost/postgres"
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
routes/index.js
/*
* GET home page.
*/
exports.index = function(req, res){
var client = new pg.Client(conString);
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
client.query('SELECT NOW() AS "theTime"', function(err, result) {
if(err) {
return console.error('error running query', err);
}
console.log(result.rows[0].theTime);
//output: Tue Jan 15 2013 19:12:47 GMT-600 (CST)
client.end();
});
});
I got the error in the browser:
Express 500 ReferenceError: pg is not defined
Can you guys give me a clue?
Best Regards
A simple way of passing anything to route handlers (whether they are declared in different files or not) in Express is to use app.locals:
// app.js
...
var app = express();
...
app.locals.someVar = someValue;
...
// somewhere else
module.exports.myhandler = function(req, res) {
var someVar = req.app.locals.someVar;
...
};
// app.js
var routes = require('./routes/index')({ varname: thevar });
...
...
And
// /routes/index.js
module.exports = function(options) {
var moduleVar = options.varname;
return {
someMethod: function (req, res) { var i = moduleVar + 2; // etc},
anotherMethod: function (req, res) {}
};
};
I do this when I create a connection (or connection pool) and simply want my modules to have access to the db without having to create another connection. All depends on your project of course, one of my hit tracking modules uses it's own connection, so I pass it the db info and from there it does it's own thing. This allows me to have multiple apps using this tracker module while each connecting to their own db.
You could define the variable without the var keyword to make the variable global.
//server.js
app.use('/shelf', require('./books').middleware);
//books.js
var app = new express.Router();
app.post('/books' , function (req, res) {
console.log('here');
});
module.exports = app;
This is what i did so far; my server runs under server.js, and when i make a '/shelf/books' request, it first goes to server.js and then to the books.js file and logs 'here'. but i want to add a request handler(a different file, handler.js i.e) where i want to to validate if the post param is a number and than redirect it to books.js if it is.
app.js
var express = require('express')
, http = require('http')
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(require('./handler').middleware);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
handler.js
var express = require('express')
var books = require('./books')
var router = new express.Router();
router.get('/shelf/:book_id', function(req, res){
var onlyNumbers =req.param('book_id').match(/^\d+$/)
if (onlyNumbers){
var parsedNumber = parseInt(req.param('book_id'));
if( parsedNumber ) {
books(parsedNumber)
console.log("Parsed number is : " + parsedNumber)
res.end("Parsed number is : " + parsedNumber)
}
}
else {
console.log("not a number : " + req.param('book_id'))
res.end("not a number : " + req.param('book_id'))
}
res.end('');
})
module.exports = router;
books.js
var express = require('express')
var app = new express.Router();
module.exports = function(req, res) {
console.log("\t in books module")
};
How about this?
//handler.js
module.exports = function (req, res, next) {
req.check_result = /\d+/.test(req.body.yourfield);
};
// book.js
app.post('/books' , function (req, res) {
if(req.check_result) {
// your code
} else {
// your code
}
});
// server.js
app.use('/shelf', require('./handler'));
app.use('/shelf', require('./books').middleware);
I am trying to set up a simple mongodb test server within my app.js node application but I keep getting "TypeError: Cannot read property 'arbiterOnly' of undefined". I am running it on local host and I have installed mongo db by running npm install mongodb in the folder I am making the application in. any help one what I am doing wrong would be greatly apreciated
here is my code for my application
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var Db = require('mongodb').Db;
var Server = require('mongodb').Server;
var client = new Db('test', new Server('localhost:', 3100, {}));
var insertData = function(err, collection) {
collection.insert({name: "Kristiono Setyadi"});
collection.insert({name: "Meghan Gill"});
collection.insert({name: "Spiderman"});
// you can add as many object as you want into the database
}
var removeData = function(err, collection) {
collection.remove({name: "Spiderman"});
}
var updateData = function(err, collection) {
collection.update({name: "Kristiono Setyadi"}, {name: "Kristiono Setyadi", sex: "Male"});
}
var listAllData = function(err, collection) {
collection.find().toArray(function(err, results) {
console.log(results);
});
}
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
client.open(function(err, pClient) {
client.collection('test_insert', insertData);
// client.collection('test_insert', removeData);
// etc.
});
var people = [{name:'Keth',age:'33',email:'ktater#gmail.com'},
{name:'Donny',age:'20',email:'donjuan86#hotmail.com'},
{name:'Loran',age:'26',email:'geegeenat#facebook.com'},
{name:'Max',age:'18',email:'axxanan#gmail.com'}];
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/users', user.list);
app.get('/people', function(req, res){
res.render('peeps', {people:people});
});
app.get('/people/:id', function(req, res){
var guy;
for (var i =0 ; i < people.length ; i++)
{
if(people[i].name == req.params.id)
guy = people[i];
}
res.render('viewPerson', {guy:guy});
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
My first guess here is that the connection is not opening. Try logging err with console.log in the client.open function. Also, the post you're getting your test code from is about 18 months old, it's possible that the code is out of date.