I am trying to connect to mongodb using below code:
var restify = require('restify');
var mongojs = require('mongojs');
var ip_addr = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
console.log('ip_addr: ' + ip_addr + ' port ' + port);
var server = restify.createServer({name: 'myproject'});
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.CORS());
server.listen(port, ip_addr, function(){
console.log(server.name + ' listening at url ' + server.url);
});
var connectionString = '127.0.0.1:27017/myproject';
if(process.env.OPENSHIFT_MONGODB_DB_PASSWORD){
connectionString = process.env.OPENSHIFT_MONGODB_DB_USERNAME + ':' +
process.env.OPENSHIFT_MONGODB_DB_PASSWORD + '#' +
process.env.OPENSHIFT_MONGODB_DB_HOST + ':' +
process.env.OPENSHIFT_MONGODB_DB_PORT + '/' +
process.env.OPENSHIFT_APP_NAME;
}
console.log('~~ connectionString: '+connectionString);
var db = mongojs(connectionString, ['accounts']);
var accounts = db.collection('accounts');
console.log('~~ db: '+ db + ' accounts:' + accounts);
var ACNT_PATH = '/accounts';
// get all records
server.get({path: ACNT_PATH, version:'0.0.1'}, findAllAccounts);
// defining call backs
function findAllAccounts(req, res, next){
res.setHeader('Access-Control-Allow-Origin', '*');
console.log('~~ Before firing query to accounts');
db.accounts.find(function(err, docs){
if(docs){
console.log('About to return docs');
res.send(200, docs);
return next();
}
console.log('about to return error');
return next(err);
});
}
It is working fine till this line: console.log('~~ Before firing query to accounts');. After which it shows this error in browser:
{"code":"InternalError","message":"Object function Object() { [native code] } has no method 'assign'"}
Any ideas, what could be wrong over here?
I solved the problem by adding below line at top of app.js file:
Object.assign = require('object-assign')
Reference link: Object function Object() { [native code] } has no method 'assign' #120
Related
I am currently building a nodejs webrtc video conference, hosted on azure. The program works perfectly fine locally, but when hosted there seems to be an issue with websockets. The client side error is below:
WebSocket connection to '<URL>' failed: WebSocket is closed before the connection is established.
index.js:83 WebSocket connection to 'wss://etuition.azurewebsites.net:8080/socket.io/?EIO=3&transport=websocket' failed: WebSocket is closed before the connection is established.
I have seen other stack overflow posts claiming that this is due to SSL, but site is currently running on HTTPS so this should not be a problem for me. Is it possible that the ws server is insecure even though my http server is secure?
Any other advice on what could be the problem will be greatly appreciated.
Below I have included my server.js code.
Please ask if any more information is needed:
/**
* Server module.
*
*
*/
'use strict';
var environment = process.env.RTC_ENV || 'local';
var debug = require('debug')('expressapp:server');
var express = require('express');
var cors = require('cors');
const http = require('http');
var logger = require('./logger').logger(environment);
var serverPort = normalizePort(process.env.PORT || '8080');
//var serverPort = normalizePort(process.env.PORT || '8080');
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
//var serverPort = process.env.RTC_PORT || 31000
var serverIpAddress = process.env.RTC_IP || 'localhost'
var socketIoServer = 'etuition.azurewebsites.net' + ':' + serverPort;
////////////////////////////////////////////////
// SETUP SERVER
////////////////////////////////////////////////
var app = express();
app.set('port', serverPort);
function redirectSec(req, res, next) {
if (req.headers['x-forwarded-proto'] == 'http') {
var redirect = 'https://' + req.headers.host + req.path;
console.log('Redirect to:' + redirect);
res.redirect(redirect);
} else {
return next();
}
}
app.use(redirectSec);
require('./router')(app, socketIoServer, environment);
// Static content (css, js, .png, etc) is placed in /public
app.use(express.static(__dirname + '/public'));
app.use(cors());
// Location of our views
app.set('views', __dirname + '/views');
// Use ejs as our rendering engine
app.set('view engine', 'ejs');
// Tell Server that we are actually rendering HTML files through EJS.
app.engine('html', require('ejs').renderFile);
const server = http.createServer(app);
server.listen(serverPort);
server.on('listening', onListening);
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
logger.info("Socket IO Address:" + socketIoServer);
logger.info("Server IP Address:" + serverIpAddress);
logger.info('Server running on port ' + serverPort);
}
var io = require('socket.io').listen(server, { log: false, origins: '*:*' });
////////////////////////////////////////////////
// EVENT HANDLERS
////////////////////////////////////////////////
io.sockets.on('connection', function (socket) {
function log() {
var array = [">>> Message from server: "];
for (var i = 0; i < arguments.length; i++) {
array.push(arguments[i]);
}
socket.emit('log', array);
}
socket.on('message', function (message) {
log('Got message: ', message);
logger.info("message: ", message);
socket.broadcast.to(socket.room).emit('message', message);
});
socket.on('create or join', function (message) {
var room = message.room;
socket.room = room;
var participantID = message.from;
configNameSpaceChannel(participantID);
io.of('/').in(room).clients(function (error, clients) {
var numClients = clients.length;
log('Room ' + room + ' has ' + numClients + ' client(s)');
log('Request to create or join room', room);
if (numClients == 0) {
logger.info(participantID + " joined first. Creates room " + room);
socket.join(room);
socket.emit('created', room);
} else {
logger.info(participantID + " joins room " + room);
io.sockets.in(room).emit('join', room);
socket.join(room);
socket.emit('joined', room);
}
})
});
// Setup a communication channel (namespace) to communicate with a given participant (participantID)
function configNameSpaceChannel(room) {
var nsp = '/' + room;
var socketNamespace = io.of(nsp);
logger.info('ConfigNameSpaceChannel:' + nsp);
socketNamespace.on('connection', function (socket) {
socket.on('message', function (message) {
// Send message to everyone BUT sender
socket.broadcast.emit('message', message);
});
});
return socketNamespace;
}
});
I'm trying to learn node.js by writing chat programs. I already got the main functionality, however when I tried to add my CSS file I made some changes to the netcode to try and include static files (line 11) and now the server doesn't send data to the client. Instead, I receive an empty response error. Here is my server code.
var express = require('express');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
var app = express();
http.listen(3000, function(){
console.log('listening on *:3000');
});
app.use(express.static('public'))
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
//connect
var address = socket.handshake.address;
console.log('connection from ' + address);
io.emit('connection from ' + address);
var user = address;
//bring up to speed
var contents = fs.readFileSync(__dirname + '/log.txt', 'utf8');
io.emit('up2speed', contents);
console.log('bringing ' + user + ' up to speed...');
//change name
socket.on('set_user', function(nick){
console.log('changing ' + user + ' to ' + nick + '...')
user = nick;
})
//message
socket.on('send_mes', function(msg){
console.log(user + ' : ' + msg);
io.emit('send_mes', user + ' : ' + msg)
fs.appendFileSync('log.txt', user + ' : ' + msg + '\n');
});
});
I've tried retracing my steps but that just put me where I started. A page with no CSS.
I have a node server running on port 3000 to serve api request.
this works fine...
http://www.skoolaide.com:3000/api/accounts
this does not.
https://www.skoolaide.com:3000/api/accounts
Can someone tell me why? If you go to https://www.skoolaide.com, the ssl cert is configured correctly, but do I need to do something on the node side?
this is my server js file. Please note: is only runs the middleware(api) on port 3000. For some reason I cannot access the middleware via https...
'use strict';
var express = require('express');
var router = express.Router();
var app = express();
var http = require('http');
var open = require('open');
var cors = require('cors');
var path = require('path');
var morgan = require('morgan');
var errorhandler = require('errorhandler');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var config = require('./config/config');
var jwt = require('jsonwebtoken');
var compression = require('compression');
var runMiddleware = require('run-middleware')(app);
var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var multer = require('multer');
var node_xj = require("xls-to-json");
var moment = require('moment');
var async = require('async');
var btoa = require('btoa');
var sharp = require('sharp');
var students = require("./middleware/students.api");
var accounts = require("./middleware/accounts.api");
var messages = require("./middleware/messages.api");
var advocates = require("./middleware/advocates.api");
var authenticate = require("./middleware/authenticate.api");
var email = require("./middleware/email.api");
var text = require("./middleware/text.api");
var colleges = require("./middleware/colleges.api");
var amazon = require("./middleware/amazon.api");
var rewards = require("./middleware/rewards.api");
var files = require("./middleware/files.api");
var validations = require("./middleware/validations.api");
var points = require("./middleware/points.api");
var notifications = require("./middleware/notifications.api");
var notificationsMap = require("./middleware/notificationsMap.api");
var trivia = require("./middleware/trivia.api");
var tasks = require("./middleware/rewardgoals.api");
var classes = require("./middleware/classes.api");
var connections = require("./middleware/connections.api");
var badges = require("./middleware/badges.api");
var fixpasswords = require("./middleware/fixpasswords.api");
var Files = require('./models/files');
mongoose.connect(config.database);
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Mongoose disconnected on app termination');
process.exit(0);
});
});
// use body parser so we can get info from POST and/or URL parameters
app.use(bodyParser.json({
limit: '50mb'
}));
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: true
}));
app.set('uploads', path.join(__dirname, 'uploads'));
app.get("/uploads/*", function (req, res, next) {
res.sendFile(__dirname + req.url);
});
var whitelist = ['https://www.skoolaide.com', 'https://skoolaide.com'];
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (whitelist.indexOf(req.headers['origin']) !== -1) {
corsOptions = { origin: true, credentials: true } // reflect (enable) the requested origin in the CORS response
} else {
corsOptions = { origin: false, credentials: false } // disable CORS for this request
}
callback(null, corsOptions) // callback expects two parameters: error and options
}
app.use(cors(corsOptionsDelegate));
//this is used because the body parser removes undefined values from the database.
app.set('json replacer', function (key, value) {
// undefined values are set to `null`
if (typeof value === "undefined") {
return null;
}
return value;
});
app.use(multer({
dest: './uploads/',
rename: function (fieldname, filename) {
return filename.replace(/\W+/g, '-').toLowerCase() + Date.now()
},
onFileUploadStart: function (file) {
//console.log(file.fieldname + ' is starting ...')
},
onFileUploadData: function (file, data) {
//console.log(data.length + ' of ' + file.fieldname + ' arrived')
},
onFileUploadComplete: function (file) {
//console.log(file.fieldname + ' uploaded to ' + file.path)
}
}).any());
// "files" should be the same name as what's coming from the field name on the client side.
app.post("/api/upload", function (req, res) {
//console.log(req.files[0].mimetype)
fs.readFile(req.files[0].path, function (err, data) {
var newPath = __dirname + "/uploads/" + req.headers["account_id"] + '_' + moment().format('MM_DD_YYYY_HH-mm-ss') + '_' + req.files[0].originalname.replace(/[^a-zA-Z0-9.]/g, '_');
var readPath = "/uploads/" + req.headers["account_id"] + '_' + moment().format('MM_DD_YYYY_HH-mm-ss') + '_' + req.files[0].originalname.replace(/[^a-zA-Z0-9.]/g, '_');
if(req.files[0].mimetype.indexOf('image') > -1){
sharp(data)
.rotate()
.resize(800, 800)
.max()
.toFile(newPath, function(err, info){
var file = new Files();
file.owner = req.headers.account_id || null;
file.classId = req.body.classId || null;
file.rewardGoalId = req.body.rewardGoalId || null;
file.avatarId = req.body.avatarId || null;
file.mimeType = req.files[0].mimetype || null;
file.originalName = req.files[0].originalname || null;
file.path = readPath;
file.save(function (err, newFile) {
if (err) {
res.send(err);
} else {
res.send({ success: true, data: newFile }).end();
}
});
});
} else{
//not an image file...
var newPath = __dirname + "/uploads/" + req.headers["account_id"] + '_' + moment().format('MM_DD_YYYY_HH-mm-ss') + '_' + req.files[0].originalname.replace(/[^a-zA-Z0-9.]/g, '_');
//console.log('Writing file: ', newPath);
fs.writeFile(newPath, data, function (err) {
var readPath = "/uploads/" + req.headers["account_id"] + '_' + moment().format('MM_DD_YYYY_HH-mm-ss') + '_' + req.files[0].originalname.replace(/[^a-zA-Z0-9.]/g, '_');
//console.log(readPath)
var file = new Files();
file.owner = req.headers.account_id || null;
file.classId = req.body.classId || null;
file.rewardGoalId = req.body.rewardGoalId || null;
file.profileId = req.body.profileId || null;
file.mimeType = req.files[0].mimetype || null;
file.originalName = req.files[0].originalname || null;
file.path = readPath;
file.save(function (err, newFile) {
if (err) {
res.send(err);
} else {
res.send({ success: true, data: newFile }).end();
}
});
});
}
});
});
app.use(express.static('www'))
var a = ['/'];
//all get requests resolve to index.
app.get(a, function (req, res) {
console.log('This is a test', req.originalUrl, req.url);
res.setHeader('Cache-Control', 'private, no-cache, no-store, must-revalidate');
res.setHeader('Expires', '-1');
res.setHeader('Pragma', 'no-cache');
res.setHeader('X-UA-Compatible', 'IE=Edge,chrome=1');
res.setHeader('Judson', 'Rocks!');
if (req.originalUrl == '/') {
res.sendFile('www/index.html', {root: __dirname});
}
});
app.set("superSecret", config.secret)
//var upload = require("./middleware/upload.api");
app.use('/api', router);
app.use('/api/students', students);
app.use('/api/accounts', accounts);
app.use('/api/messages', messages);
app.use('/api/advocates', advocates);
app.use('/api/authenticate', authenticate);
app.use('/api/email', email);
app.use('/api/text', text);
app.use('/api/colleges', colleges);
app.use('/api/amazon', amazon);
app.use('/api/rewards', rewards);
app.use('/api/files', files);
app.use('/api/validate', validations);
app.use('/api/points', points);
app.use('/api/notifications', notifications);
app.use('/api/notificationsMap', notificationsMap);
app.use('/api/trivia', trivia);
app.use('/api/rewardgoals', tasks);
app.use('/api/classes', classes);
app.use('/api/badges', badges);
app.use('/api/connections', connections);
app.use('/api/fixpasswords', fixpasswords);
/**SERVER*************************************/
// all environments
app.set('port', process.env.PORT || 3000);
app.engine('html', require('ejs').renderFile);
// express/connect middleware
app.use(morgan('dev'));
app.use(compression()); //use compression
// development only
if ('development' === app.get('env')) {
app.use(errorhandler());
}
/**END SERVER*************************************/
var cluster = require('cluster');
if (cluster.isMaster) {
var numWorkers = require('os').cpus().length;
console.log('Master cluster setting up ' + numWorkers + ' workers...');
for (var i = 0; i < numWorkers; i++) {
cluster.fork();
}
cluster.on('online', function (worker) {
console.log('Worker ' + worker.process.pid + ' is online');
});
cluster.on('exit', function (worker, code, signal) {
console.log('Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal);
console.log('Starting a new worker');
cluster.fork();
});
} else {
app.listen(app.get('port'),
function () {
console.log('myApp server listening on port ' + app.get('port'));
});
}
Your code only starts an HTTP server. This line:
app.listen(app.get('port'))
starts only an http server. If you want support for HTTPS, you have to also start an HTTPS server and you have to start it on a different port. The express doc for app.listen() shows you how to do that and it's basicaly like this:
var express = require('express');
var https = require('https');
var http = require('http');
var app = express();
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
where options contains your SSL certificates and where you fill in the desired port numbers for your http server and your https server.
If you were operating under the illusion that you don't need a port number in the browser in order to access both an http and https server, that's because the browser fills in a default port number for you. If you just type an http URL, it uses port 80. If you type an https URL with no port, it uses port 443. If you're not on those two specific ports, you have to specify the desired port in the browser URL. In either case, you need a separate server on separate ports for both http and https.
Use var https = require("https"); not
Var http = require ("http");
In here I have a http server and a net server on the same file. The net server connects to Arduino. I want to show the data received from Arduino on the http server website. Also when a button is pressed on the website, I want to send some data through the net server to the arduino. How can I do that.
var http = require("http");
var url = require('url');
var fs = require('fs');
var ip = require('ip');
var net = require('net');
var colors = require('colors');
var formidable = require('formidable');
var HOST = ip.address();//my IP address
var HTTP_PORT = 4321;
var NET_PORT = 1234;
var NAME;
var backButton;
var _p1 = '<form role="form" action="enext" method="post" enctype="multipart/form-data">'
+ '<h1>'
+ '=== Arduino Data Online ==='
+ '</h1><br><h2>'
+ 'Arduino data: ';
var _msg = 'sock data';
var _p2 = '</h2><br><br>'
+ '<h3>'
+ 'Press NEXT after fp success'
+ '</h3><br><b>'
+ '<button type="submit">'
+ 'NEXT'
+ '</button></form>';
//socket
function func(sock) {
console.log(colors.cyan('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort));
// Add a 'data' event handler to this instance of socket
sock.on('data', function (data) {
////========
console.log(data);
});
// Add a 'close' event handler to this instance of socket
sock.on('close', function (data) {
console.log(colors.cyan('CLOSED: ' + sock.remoteAddress + ' ' + sock.remoteNET_PORT));
console.log("");
httpserver.close();
});
sock.on('error', function (data) {
console.log(colors.magenta("clnt error"));
httpserver.close();
});
}
net.createServer(func).listen(NET_PORT, HOST);
console.log(colors.yellow('Server listening on ' + HOST + ':' + NET_PORT));
var httpserver = http.createServer(function (request, response) {
var path = url.parse(request.url).pathname;
console.log('CONNECTED');
console.log(path);
switch (path) {
case '/':
response.writeHead(200, { "Content-Type": "text/html" });
response.write(_p1, "utf8");
response.write(_msg, "utf8");
response.write(_p2, "utf8");
response.end();
break;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 404");
response.end();
break;
}
});
httpserver.listen(HTTP_PORT, HOST);
console.log('http://Server # ' + HOST + ':' + HTTP_PORT);
I'm running the flash socket policy server on port 8484. On the same port I need to receive http requests. I'm thinking about checking whether policy-file was requested (inside the if statement below), and if it wasn't - forwarding the http request to another port where express is running (let's say localhost:3000). How can I obtain that?
// flash socket policy server
var file = '/etc/flashpolicy.xml',
host = 'localhost',
port = 8484,
poli = 'something';
var fsps = require('net').createServer(function (stream) {
stream.setEncoding('utf8');
stream.setTimeout(10000);
stream.on('connect', function () {
console.log('Got connection from ' + stream.remoteAddress + '.');
});
stream.on('data', function (data) {
console.log(data);
var test = /^<policy-file-request\/>/;
if (test.test(data)) {
console.log('Good request. Sending file to ' + stream.remoteAddress + '.')
stream.end(poli + '\0');
} else {
console.log('Not a policy file request ' + stream.remoteAddress + '.');
stream.end('HTTP\0');
// FORWARD REQUEST TO localhost:3000 for example //
}
});
stream.on('end', function () {
stream.end();
});
stream.on('timeout', function () {
console.log('Request from ' + stream.remoteAddress + ' timed out.');
stream.end();
});
});
require('fs').readFile(file, 'utf8', function (err, poli) {
if (err) throw err;
fsps.listen(port, host);
console.log('Flash socket policy server running at ' + host + ':' + port + ' and serving ' + file);
});
I solved this problem a while ago, but have forgotten about the question :) The solution was to create a socket which made it possible to send and retrieve data between http express server and tcp flash policy server.
flash policy server:
var file = process.argv[2] || '/etc/flashpolicy.xml',
host = process.argv[3] || 'localhost',
port = process.argv[4] || 8484,
poli = 'flash policy data\n',
net = require('net'),
http = require('http');
var fsps = net.createServer(function (stream) {
stream.setEncoding('utf8');
stream.on('connect', function () {
console.log('Got connection from ' + stream.remoteAddress + '.');
});
stream.on('data', function (data) {
var test = /^<policy-file-request\/>/;
if (test.test(data)) {
console.log('Good request. Sending file to ' + stream.remoteAddress + '.')
stream.end(poli + '\0');
} else {
console.log('Not a policy file request ' + stream.remoteAddress + '.');
var serviceSocket = new net.Socket();
serviceSocket.connect(3000, 'localhost', function () {
console.log('>>>> Data from 8484 to 3000 >>>>\n', data.toString());
serviceSocket.write(data);
});
serviceSocket.on("data", function (received_data) {
console.log('<<<< Data from 3000 to 8484 to client <<<<\n', received_data.toString());
stream.write(received_data);
});
}
});
stream.on('end', function () {
console.log('tcp server disconnected');
});
stream.on('timeout', function () {
console.log('Request from ' + stream.remoteAddress + ' timed out.');
});
});
require('fs').readFile(file, 'utf8', function (err, poli) {
if (err) throw err;
fsps.listen(port, host);
console.log('Flash socket policy server running at ' + host + ':' + port + ' and serving ' + file);
});
sample express server on localhost:3000:
var express = require('express')
, http = require('http')
, path = require('path')
, app = express();
// all environments
app.set('port', process.env.PORT || 3000);
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')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', function(req, res){
res.send('Proper HTTP response');
});
app.post('/', function(req, res){
console.log(req.body);
res.send('Proper HTTP response');
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express HTTP server listening on port ' + app.get('port'));
});