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);
Related
I create web applications using NodeJS and ExpressJS, I use the https server. I would like all the devices connected to the same network not to enter the ip address of the localhost, and instead could enter, for example: https://SmartphoneMonitoring.com and would be redirected to the localhost
server script:
var connections = [];
var express = require('express');
var bodyParser = require('body-parser')
var expressValidator = require('express-validator');
var hbs = require('hbs'); //handlebars
var session = require('express-session');
var cookieParser = require('cookie-parser');
var fs = require('fs');
var routes = require('./routes/router');
var https = require('https');
var path = require('path');
var mysql = require('mysql');
var dns = require('dns');
dns.resolve4('www.google.com', function (err, addresses) {
if (err) throw err;
console.log('addresses: ' + JSON.stringify(addresses));
addresses.forEach(function (a) {
dns.reverse(a, function (err, domains) {
if (err) {
console.log('reverse for ' + a + ' failed: ' + err.message);
} else {
console.log('reverse for ' + a + ': ' + JSON.stringify(domains));
}
});
});
});
var databasePort = 3306;
var dataBaseName = 'BazaDanych';
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
port: databasePort,
database: dataBaseName
});
setTimeout(function(){connectToDB()},1000);
function connectToDB(){
db.connect((err) =>{
if(err){
console.log(err);
} else {
console.log('Połączono z bazą danych na porcie: ' + databasePort)
}
});
};
var app = express();
const httpsOptions = {
cert: fs.readFileSync(path.join(__dirname, 'ssl', 'server.crt')),
key: fs.readFileSync(path.join(__dirname, 'ssl', 'server.key'))
};
var server = https.createServer(httpsOptions, app);
var io = require('socket.io', { rememberTransport: false, transports: ['WebSocket', 'Flash Socket', 'AJAX long-polling'] }).listen(server);
app.set('views', (__dirname, 'views'));
app.set('view engine', '.hbs');
hbs.registerHelper('json', function(obj){
return new hbs.SafeString(JSON.stringify(obj));
})
//Partials
const partialsDir = __dirname + '/views/partials';
const filenames = fs.readdirSync(partialsDir);
filenames.forEach(function (filename) {
const matches = /^([^.]+).hbs$/.exec(filename);
if (!matches) {
return;
}
const name = matches[1];
const template = fs.readFileSync(partialsDir + '/' + filename, 'utf8');
hbs.registerPartial(name, template);
});
//Partials
hbs.registerHelper('ifequal',function(a, b,options)
{
if (a==b){
return options.fn(this);
} else {
return options.inverse(this);
}
});
var serverPort = 3030;
server.listen(serverPort, function(){
console.log("Połączono z serwerem na porcie: " + serverPort);
})
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(expressValidator());
app.use(cookieParser());
app.use(session({
key: 'user_sid',
secret: 'fsdfdsfsdfsdfsdfsdf',
resave: false,
saveUninitialized: false
}));
app.use('/', routes);
I tried to get the effect using DNS but it did not bring the expected results.
I have a nodejs app running on Heroku. Here is the server.js file
var express = require('express')
, cors = require('cors')
, app = express();
var http = require('http').Server(app);
var io = require("socket.io").listen(http);
app.use(cors());
require('./modules/routes.js')(app,io);
app.set('port', process.env.PORT || 5000);
app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
Here is my routes.js
"use strict";
const bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var time = require('express-timestamp');
var Promise = require('promise');
var momentjs = require('moment');
var _ = require('lodash');
var method = routes.prototype;
function routes(app, io) {
app.use(time.init);
app.use(cookieParser());
app.use(session({ secret: 'asdo8rter65edfgfd53wet34634632y4bluaq', resave: true, saveUninitialized: true }));
app.all('/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.use(bodyParser.json());
app.post('/testHeroku', function(req, res) {
console.log(req);
res.write(JSON.stringify({
process: "success"
}));
res.end();
});
}
method.getroutes = function() {
return this;
}
module.exports = routes;
I'm trying to access /testHeroku from an ionic app running in android emulator.
Ionic code:
vm.testHeroku = function(){
console.log('testing heroku');
var testdata = {
url: config.baseURL + 'testHeroku',
dataServer: {
serverTaskRequest: 'getUADSF'
}
}
runajax.runajax_function(testdata, function (testdataResponse) {
if (testdataResponse.process == 'success') {
alert(testdataResponse.process);
}
});
};
Here goes my config.baseURL = abcd-1234.herokuapp.com (This is example for the heroku app url)
I don't receive any return form the http call.
Code for run_ajax service
.service('runajax', ['$http', function ($http) {
this.runajax_function = function (request, callback) {
var url = request.url;
var dataServer = request.dataServer;
// console.log('runajax function called -> ' + url);
// console.log(dataServer);
$http.post(url, dataServer).success(function (data, status, headers, config) {
callback(data);
})
.error(function () {
callback(status);
});
}
}])
I got it working. There was an error with app.set('port', process.env.PORT || 5000); I changed it to var port = process.env.PORT || 8080;
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() ));
});
I am new to node.js. I am developing node js application using VS 2015. Below is my server code (app.js)
In one of routes (trains.js) I defined a simple post method like below. Thing is it is working fine from localhost. But once I deploy to azure websites, POST method is throwing Internal server error.
Can some one help me with this? Please let me know if you need any further details.
//Here is my app.js
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 socketio = require('socket.io');
var global = require('./routes/globals.js');
GLOBAL._ = require('lodash');
GLOBAL.KEY = 'xxxxxxxxxxxxxxxxxxxxxx';
var availability = require('./routes/availability');
var fare = require('./routes/fare');
var stations = require('./routes/stations');
var pnr = require('./routes/pnr');
var route = require('./routes/route');
var trains = require('./routes/trains');
var app = express();
app.socket = socketio();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.set('port', process.env.PORT || 3000);
app.use('/availability', availability);
app.use('/fare', fare);
app.use('/stations', stations);
app.use('/pnr', pnr);
app.use('/route', route);
app.use('/trains', trains);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.socket.on('connection', function (socket) {
socket.on('message', function (msg) {
console.log('Message Received: ', msg);
socket.broadcast.emit('message', msg);
});
});
global.io = app.socket;
module.exports = app;
//Here is my train.js
var express = require('express');
var http = require('http');
var router = express.Router();
var utils = require("./utils.js");
var global = require('./globals.js');
router.get('/', function (req, res) {
var options = {
host: 'www.xxxxxxx.com',
path: '/test/xxxxxx/'
};
var parameters = {
fscode : 'xxxx',
tscode: 'xxxx',
//date: '',
//'class': '',
//orderby: '',
format: 'json',
pbapikey: '9xxxxxxxxa'
};
options.path += utils.getQueryString(parameters);
options.path += "pbapisign/" + utils.getHmacSHA1Signature(parameters);
callback = function (response) {
var data = "";
response.on('data', function (chunk) {
data += chunk;
});
response.on('end', function () {
console.log(data);
res.send(data + "<h1>" + utils.hello() + "</h1>");
});
}
http.request(options, callback).on('error', function (error) {
console.log(error);
res.status(400).send(error.Message)
}).end();
});
router.post('/check', function (req, res) {
// console.log('Request -', req);
// console.log('Response -', res);
var data = {
request : "HELLO",
response: "VAMSI"
}
global.io.sockets.emit('NEW_CONTACT', data);
res.status(200).send('NEW DATA').end();
});
module.exports = router;
It seems that your code has not any obvious bug.
So if you can share some information for more detail, such as for error or deployment, I think it's helpful for investigating the issue.
Meanwhile, please try to install NTVS for your VS2015 and follow the wiki page Advanced Debugging - Remote Debugging on Windows Azure to debug your application.
I'm just learning testing and I've been at it for a few hours no with no success. Every time I run Mocha, my test shows up in the terminal and returns no result, like this:
Express test app started on port: 3001
addition
It stays blank afterwards. Further, the node processes don't close after testing and when they stack up they crash my computer.
Here is my sample test:
var supertest = require('supertest');
var should = require('should');
process.env.NODE_ENV = 'test';
var app = require('../server');
describe('addition', function() {
//... previous test
it('should return 2 given the url /add/1/1', function(done) {
request(app)
.get('/add/1/1')
.expect(200)
.end(function(err, res) {
should.not.exist(err);
parseFloat(res.text).should.equal(2);
done();
});
});
});
Here is my server.js
// Module Depndencies
var express = require('express'),
fs = require('fs'),
mongoose = require('mongoose'),
passport = require('passport'),
MongoStore = require('connect-mongo')(express),
flash = require('connect-flash'),
env = process.env.NODE_ENV = process.env.NODE_ENV || 'development',
ErrorHandler = require('./app/controllers/api/v1/error_handler_v1'),
config = require('./config/config'),
auth = require('./config/middlewares/authorization');
// Connect The Database
mongoose.connect(config.db);
// Catch Database Connection Error
mongoose.connection.on("error", function(err) {
return console.log("****** Could not connect to mongo server!");
});
// Express Settings
app = express();
app.set('showStackError', true);
//Should be placed before express.static
app.use(express.compress({
filter: function(req, res) {
return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
},
level: 9
}));
//Setting the fav icon and static folder - tejkh
app.use(express.favicon());
app.use(express.static(config.root + '/public'));
//Don't use logger for test env
if (process.env.NODE_ENV !== 'test') app.use(express.logger('dev'));
//Set views path, template engine and default layout
app.set('views', config.root + '/app/views');
app.set('view engine', 'jade');
// Enable jsonp
app.enable('jsonp callback');
//Bootstrap models
var models_path = __dirname + '/app/models';
var walk = function(path) {
fs.readdirSync(path).forEach(function(file) {
var newPath = path + '/' + file;
var stat = fs.statSync(newPath);
if (stat.isFile()) {
if (/(.*)\.(js|coffee)/.test(file)) {
require(newPath);
}
} else if (stat.isDirectory()) {
walk(newPath);
}
});
};
walk(models_path);
// Bootstrap Passport
require('./config/passport')(passport);
// App.configure
app.configure(function() {
// CookieParser should be above session
app.use(express.cookieParser());
// BodyParser should be above methodOverride
app.use(express.bodyParser());
app.use(express.methodOverride());
// Express/mongo session storage
app.use(express.session({
secret: 'secret',
cookie: {
maxAge: 864000000 // 10 Days in miliseconds
},
store: new MongoStore({
url: config.db,
auto_reconnect: true
})
}));
// Connect flash for flash messages
app.use(flash());
// Use Passport
app.use(passport.initialize());
app.use(passport.session());
// Route
app.use(app.router);
// Error Handler
app.use(function(err, req, res, next) {
if (err.uri) delete err.uri;
if (err.status) {
return res.status(err.status).jsonp(err);
} else {
res.status(500).jsonp({
name: 'InternalError',
message: 'Sorry, something went wrong on our end. We have been notified.',
code: 'server_error',
status: 500
});
}
});
}); // app.configure
//Bootstrap routes
require('./config/routes')(app, passport, auth);
// Start App
app.listen(config.port);
console.log('Express ' + env + ' app started on port: ' + config.port);
// Expose app
exports = module.exports = app;
If you use:
var supertest = require('supertest');
then you should use:
supertest(app)
and not:
request(app)
try this, maybe it will work
request('http://host:port')