WebSocket Connection failed: error in connection establishment - javascript

The following code is client and server side code to use webRTC connection. It's working perfectly in localhost. when i deployed to linux shared hosting server., it's getting error.
This is my server side code.
var http = require('http');
var express = require('express');
var ExpressPeerServer = require('peer').ExpressPeerServer;
var app = express();
var server = http.createServer(app);
var options = {
debug: true,
key: 'peerjs',
allow_discovery: true,
ssl: {
key: '',
cert: ''
},
proxied: true
};
var expressPeerServer = ExpressPeerServer(server, options);
app.use('/api', expressPeerServer);
app.use('/', express.static('.'));
app.use('/list', function (req, res) {
return res.json(Object.keys(expressPeerServer._clients.peerjs));
});
var port = process.env.PORT || 8080;
server.listen(port, function () {
console.log('Basic-ss live at', port);
});
expressPeerServer.on('connection', function (id) {
console.log('Peer connected with id:', id);
});
expressPeerServer.on('disconnect', function (id) {
console.log('Peer %s disconnected', id);
});
the following is the client side code for connect peer.
initPeer(peerId) {
this.peer = new Peer(peerId, {
host: 'localhost',
port: 8080,
path: '/api',
key: 'peerjs',
debug: 3,
config: {
'iceServers': [
{ url: 'stun:stun.l.google.com:19302' },
]
}
});
setTimeout(() => {
this.currentPeerId = this.peer.id;
if (this.currentPeerId !== null) {
isPeerConnected = true;
} else {
isPeerConnected = false;
}
console.log('Current Peer ID', this.currentPeerId);
}, 4000);
}
this code is working perfectly in localhost.
this is the code i am uploading in server.
this.peer = new Peer(peerId, {
host: '', ===> my domain name here.
port: 8080,
path: '/api',
key: 'mebstelemedclinic',
debug: 3,
config: {
'iceServers': [
{ url: 'stun:stun.l.google.com:19302' },
{
url: 'turn:192.158.29.39:3478?transport=udp',
credential: 'JZEOEt2V3Qb0y27GRntt2u2PAYA=',
username: '28224511:1379330808'
}
]
}
});
if use the same server code and the above client side code., it's getting connection error.
WebSocket connection to 'wss://mydomain.in:8080/api/peerjs?key=peerjs&id=LY42201PH-yKy04f-ygqZJhqrBmezG6&token=n42tatqqn9e' failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT
i was struck at this point from long time. Help me how can i overcome this error. thank you.

You should add the code below to your path nano site_name in /etc/nginx/sites-available:
location {
proxy_pass Ip address; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; }

Related

Why am I getting 'timeout' error on socket.io and self-signed ssl connection

I created a nodejs server with https. There is no problem when making a GET request, but when connecting with another nodejs application that works with socket.io-client, I get the error 'WebSocket was closed before the connection was established'. What could be the reason?
server.js:
import https from 'https';
import fs from 'fs';
import { Server } from 'socket.io';
const options = {
key: fs.readFileSync('../certs/server-key.pem'),
cert: fs.readFileSync('../certs/server-crt.pem'),
ca: [
fs.readFileSync('../certs/client-ca-crt.pem')
],
requestCert: true,
rejectUnauthorized: false
};
const server = https.createServer(options);
const io = new Server(server, { serveClient: false });
io.sockets.on('connection', function (socket) {
console.log(socket.id);
});
server.listen({ port: 8443, host: 'localhost' }, () => {
console.log(server.address());
});
client.js:
import { io } from 'socket.io-client';
import fs from 'fs';
const socket = io('https://server.aaa.com:8443', {
hostname: 'server.aaa.com',
transports: ['websocket'],
key: fs.readFileSync('../certs/client-key.pem'),
cert: fs.readFileSync('../certs/client-crt.pem'),
ca: [
fs.readFileSync('../certs/server-ca-crt.pem')
],
rejectUnauthorized: false,
reconnection: false
});
socket.on('connect', () => {
console.log(socket.id);
});
socket.on("error", (err) => {
console.log(err);
});
socket.on("connect_error", (err) => {
console.log(err);
});
No problem with that:
const fs = require("fs");
const https = require("https");
const message = { msg: "Hello!" };
const req = https.request(
{
host: "server.aaa.com",
port: 8443,
key: fs.readFileSync(`../certs/client-key.pem`),
cert: fs.readFileSync(`../certs/client-crt.pem`),
ca: [
fs.readFileSync(`../certs/server-ca-crt.pem`)
],
path: "/",
method: "GET",
},
function(response) {
let rawData = "";
response.on("data", function(data) {
rawData += data;
});
response.on("end", function() {
if (rawData.length > 0) {
console.log(`Received message: ${rawData}`);
}
console.log(`TLS Connection closed!`);
req.end();
return;
});
}
);
req.on("socket", function(socket) {
socket.on("secureConnect", function() {
if (socket.authorized === false) {
console.log(`SOCKET AUTH FAILED ${socket.authorizationError}`);
}
console.log("TLS Connection established successfully!");
});
socket.setTimeout(10000);
socket.on("timeout", function() {
console.log("TLS Socket Timeout!");
req.end();
return;
});
});
req.on("error", function(err) {
console.log(`TLS Socket ERROR (${err})`);
req.end();
return;
});
req.write(JSON.stringify(message));
output:
TLS Connection established successfully!
Received message: OK!
TLS Connection closed!
I finally found the solution to the problem.
I need to add the following code for socket.io to use the default socket.io path (/socket.io).
io.listen(server);
server.js
import https from 'https';
import fs from 'fs';
import { Server } from 'socket.io';
const options = {
key: fs.readFileSync('../certs/server-key.pem'),
cert: fs.readFileSync('../certs/server-crt.pem'),
ca: [
fs.readFileSync('../certs/client-ca-crt.pem')
],
requestCert: true,
rejectUnauthorized: false
};
const server = https.createServer(options);
const io = new Server(server);
io.listen(server);
io.on('connection', function (socket) {
console.log(socket.id);
});
server.listen({ port: 9443, host: 'localhost' }, () => {
console.log(server.address());
});
Your server is listening on localhost, but the client is trying to connect to server.aaa.com. So you have to make the server listen on server.aaa.com or 0.0.0.0.

Node hapi app starts, but doesnt appear to bind to port

I have an hapi app that is in development. Upon running my usual node-foreman with Procfile, the app loads in the command line with no errors, but upon browsing to the configured port, the page errors, no connection, or specifically, connection refused. Back to the CLI, no errors. simple message from the server.start "Server running on http://localhost:3000"
I tried directly launching with gulp (no errors). No browser access.
I tried directly launching with node (no errors). No browser access.
I tried creating a hello world app with hapi, and express, both had no errors and DID load in the browser.
I even version controlled the code back to a version I know worked. Starts server fine from CLI, but no browser loading/access.
I'm a little stuck, would love any thoughts on even a path to go down to trouble shoot.
Thank you in advance.
Here is the app JS:
var config = require('./config');
hapi = require('../lib/hapi'),
chalk = require('chalk'),
module.exports.init = function (callback) {
//init app bserver
server = hapi.init();
callback(server, config );
};
module.exports.start = function (callback) {
var _this = this;
_this.init(function (server, config) {
// Start the app by listening on <port>
server.start(function () {
// Logging initialization
console.log('+-----------------------------------------------------------+');
console.log(chalk.green('| ' + config.app.title+ '\t\t\t|'));
console.log('+-----------------------------------------------------------+');
console.log(chalk.green('| Environment:\t' + process.env.NODE_ENV));
console.log(chalk.green('| Standard Port:\t' + config.port));
if (config.https.ssl === true ) {
console.log(chalk.green('| Secure Port:\t' + config.https.port));
console.log(chalk.green('| HTTPs:\t\ton'));
}
console.log(chalk.green('| App version:\t' + config.version));
console.log(chalk.green('| App url:\t\t' + ((config.https.ssl === true ? 'https' : 'http')+"://"+config.url)));
console.log('+-----------------------------------------------------------+');
console.log('| Database Configuration\t\t\t\t\t|');
console.log('+-----------------------------------------------------------+');
console.log(chalk.green(JSON.stringify(config.db, null, 4)));
console.log('+-----------------------------------------------------------+');
if (callback) callback(server, db, config);
});
return server;
});
};
AND HERE IS THE HAPI INCLUDE:
var config = require('../general/config'),
Hapi = require('hapi'),
Good = require('good'),
Hoek = require('hoek'),
Inert = require('inert'),
Vision = require('vision'),
Path = require('path'),
Boom = require('boom'),
Bell = require('bell'),
Cookie = require('hapi-auth-cookie'),
Url = require('url'),
hapiAuthSessions = require('./sessions'),
Promise = require('bluebird'),
fs = require('fs');
/* Initialize ORM and all models */
module.exports.initDBConnections = function( server ) {
server.register([
{
register: require('hapi-sequelize'),
options: [
{
sequelize: new Sequelize(process.env.DATABASE_URL),
name: config.db.connection.database,
models: config.files.server.models,
sync: true,
forceSync:false
}
]
}
], function(err) {
Hoek.assert(!err, err);
});
}
/**
* Initialize rendering engine
*/
module.exports.initRenderingEngine = function (server) {
var paths = [];
var layouts = [];
var partials = [];
var helpers = [];
/* add each module paths to rendering search, assume if route, there is a view fr module */
config.files.server.routes.forEach(function (routePath) {
var rp = Path.relative(Path.join(__dirname,'../../'),Path.resolve(Path.dirname(routePath)+'/../../'))
if(fs.existsSync(rp+'/server/views/'+config.theme+'/content'))
paths.push(rp+'/server/views/'+config.theme+'/content');
if(fs.existsSync(rp+'/server/views/'+config.theme+'/errors'))
paths.push(rp+'/server/views/'+config.theme+'/errors');
if(fs.existsSync(rp+'/server/views/'+config.theme+'/layouts'))
layouts.push(rp+'/server/views/'+config.theme+'/layouts');
if(fs.existsSync(rp+'/server/views/'+config.theme+'/partials'))
partials.push(rp+'/server/views/'+config.theme+'/partials');
if(fs.existsSync(rp+'/server/views/'+config.theme+'/helpers'))
helpers.push(rp+'/server/views/'+config.theme+'/helpers');
});
server.views({
engines: {
html: require('handlebars')
},
path: paths,
layoutPath: layouts,
partialsPath: partials,
helpersPath: helpers,
layout: 'base.view'
});
}
/**
* Initialize local variables
*/
module.exports.initLocalVariables = function (server) {
// Setting application local variables
for (var property in config) {
if (config.hasOwnProperty(property)) {
if (!server.app[property]) {
server.app[property] = config.app[property]
}
}
}
};
/**
* Initialize static routes for browser assets
*/
module.exports.initStaticRoutes = function (server) {
server.route([{
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: Path.join(__dirname, '../../public'),
redirectToSlash: true,
listing: false,
defaultExtension: 'html'
}
}
},{
method: 'GET',
path: '/assets/vendor/{param*}',
handler: {
directory: {
path: Path.join(__dirname, '../../node_modules'),
redirectToSlash: false,
listing: false,
defaultExtension: 'js'
}
}
}]);
}
/**
* Initialize server logging
*/
module.exports.initLogging = function (server) {
return {
ops: {
interval: 1000
},
reporters: {
myConsoleReporter: [{
module: 'good-squeeze',
name: 'Squeeze',
args: [{ log: '*', response: '*' }]
}, {
module: 'good-console'
}, 'stdout']
}
};
}
/**
* Initialize App Tenant
*/
module.exports.initAppTenant = function (server) {
server.ext('onRequest', function (req, res) {
server.app['tenant'] = req.info.hostname;
res.continue();
});
};
/**
* Initialize ensure SSL
*/
module.exports.initSSL = function(server) {
server.select('http').route({
method: '*',
path: '/{p*}',
handler: function (req, res) {
// redirect all http traffic to https
console.log('redirecting',config.url + req.url.path);
return res.redirect('https://' + config.url + req.url.path).code(301);
},
config: {
description: 'Http catch route. Will redirect every http call to https'
}
});
}
/**
* Initialize static routes for modules in development mode browser assets
*/
module.exports.initModulesStaticRoutes = function(server) {
if (process.env.NODE_ENV === 'development') {
server.route({
method: 'GET',
path: '/modules/{param*}',
handler: {
directory: {
path: Path.join(__dirname, '../../modules'),
redirectToSlash: false,
listing: false,
defaultExtension: 'html'
}
}
});
}
}
/**
* Configure the modules server routes
*/
module.exports.initModulesServerConfigs = function (server) {
config.files.server.configs.forEach(function (routePath) {
require(Path.resolve(routePath))(server);
});
};
/**
* Configure the modules server routes
*/
module.exports.initModulesServerRoutes = function (server) {
config.files.server.routes.forEach(function (routePath) {
require(Path.resolve(routePath))(server);
});
};
/**
* Configure Socket.io
*/
module.exports.configureSocketIO = function (server) {
// Load the Socket.io configuration
var server = require('./socket.io')(server);
// Return server object
return server;
};
/**
* Initialize hapi
*/
module.exports.init = function init() {
var server = new Hapi.Server({
connections: {
routes: {
files: {
relativeTo: Path.join(__dirname, 'public')
}
},
state: {
isSameSite: 'Lax'
}
},
debug: {
'request': ['error', 'uncaught','all','request']
},
cache: [
{
name: 'cacheMem',
engine: require('catbox-memcached'),
host: '127.0.0.1',
port: '8000',
partition: 'cache'
},{
name : 'cacheDisk',
engine : require('catbox-disk'),
cachePath: '/var/tmp',
partition : 'cache'
}
]
});
server.connection({
labels: 'http',
port: config.port
});
if(config.https.ssl == true) {
server.connection({
labels: 'https',
port: config.https.port,
tls: {
key: config.https.key,
cert: config.https.cert
}
});
/* redirect ssl */
this.initSSL(server);
}
server.register([Vision,{register: Good, options: this.initLogging(server)},Cookie,Bell,Inert], function(err) {
Hoek.assert(!err, err);
var _this = module.exports;
var _thisServer = server.select((config.https.ssl == true ? 'https' : 'http'));
/* Initialize sessions */
hapiAuthSessions._init(_thisServer);
/* detect app tenant */
_this.initAppTenant(_thisServer);
/* app local variables */
_this.initLocalVariables(_thisServer);
/* logging */
_this.initLogging(_thisServer);
/* static file serving */
_this.initStaticRoutes(_thisServer);
/* module config, routes, static routes */
_this.initModulesStaticRoutes(_thisServer);
_this.initModulesServerConfigs(_thisServer);
_this.initModulesServerRoutes(_thisServer);
/* rendering engine */
_this.initRenderingEngine(_thisServer);
// Configure Socket.io
server = _this.configureSocketIO(_thisServer);
//server.start located in ../general/app.js
});
return server;
}
HERE IS THE CLI OUTPUT:
[13:58:31] [nodemon] starting `node --inspect server.js`
[13:58:31] [nodemon] child pid: 5596
Debugger listening on ws://127.0.0.1:9229/e2f5837f-b552-4156-b004-e7adb3d30d05
For help see https://nodejs.org/en/docs/inspector
+-----------------------------------------------------------+
| APP - Development Environment |
+-----------------------------------------------------------+
| Environment: development
| Standard Port: 3000
| Secure Port: 3001
| HTTPs: on
| App version: 0.3.0
| App url: https://localhost:3001
+-----------------------------------------------------------+
| Database Configuration |
+-----------------------------------------------------------+
{
"client": "postgresql",
"connection": {
"host": "localhost",
"port": "5432",
"database": "database",
"user": "user",
"password": "password",
"ssl": true
},
"pool": {
"min": 2,
"max": 10
},
"migrations": {
"tableName": "knex_migrations"
},
"debug": true
}
+-----------------------------------------------------------+
Ok. I found the answer (this is twice in a week over looking small detail -- Shame on me).
The smaller problem, that lead me to the larger problem, was upon server.start(callback) I didn't have any error checking, similar to:
server.start(function(err) {
if(err) {
throw err;
}
});
Once I added the err logging, it exposed the reason the server was quietly failing.
My Hapi config was requiring a memcached module, and I had not started my memcached server locally.
All back to to working as designed :)

WebSocket connection to 'ws://localhost:3000/' failed: Connection closed before receiving a handshake response

I took a game that my friend made and wanted to make it playable across browsers by sending keypress data between peers with WebRTC and websockets. However, I get this error in the console:
WebSocket connection to 'ws://localhost:3000/' failed: Connection closed before receiving a handshake response
My server file has the following few lines:
'use strict';
const express = require('express');
const SocketServer = require('ws').Server;
const path = require('path');
const PORT = process.env.PORT || 3000;
const INDEX = path.join(__dirname, 'index.html');
const server = express();
server.use(express.static(path.join(__dirname, 'lib')));
server.use('/assets', express.static(path.join(__dirname, 'assets')));
server.listen(PORT, () => console.log(`Listening on ${ PORT }`));
const wss = new SocketServer({ server });
var users = {};
let usernames = [];
wss.on('connection', function(connection) {
connection.on('message', function(message) {
var data;
try {
data = JSON.parse(message);
} catch (e) {
console.log("Invalid JSON");
data = {};
}
switch (data.type) {
case "login":
console.log("User logged", data.name);
if(users[data.name]) {
sendTo(connection, {
type: "login",
success: false
});
} else {
users[data.name] = connection;
connection.name = data.name;
usernames.push(data.name);
sendTo(connection, {
type: "login",
success: true,
users: usernames
});
}
break;
case "offer":
console.log("Sending offer to: ", data.name);
var conn = users[data.name];
if(conn != null) {
connection.otherName = data.name;
sendTo(conn, {
type: "offer",
offer: data.offer,
name: connection.name
});
}
break;
case "answer":
console.log("Sending answer to: ", data.name);
var conn = users[data.name];
if(conn != null) {
connection.otherName = data.name;
sendTo(conn, {
type: "answer",
answer: data.answer
});
}
break;
case "candidate":
console.log("Sending candidate to:",data.name);
var conn = users[data.name];
if(conn != null) {
sendTo(conn, {
type: "candidate",
candidate: data.candidate
});
}
break;
case "leave":
console.log("Disconnecting from", data.name);
var conn = users[data.name];
conn.otherName = null;
if(conn != null) {
sendTo(conn, {
type: "leave"
});
}
break;
default:
sendTo(connection, {
type: "error",
message: "Command not found: " + data.type
});
break;
}
});
And the client side of the connection looks as follows:
const Game = require("./game");
const GameView = require("./game_view");
var HOST = location.origin.replace(/^http/, 'ws');
console.log('host: ', HOST);
console.log(process.env.PORT);
document.addEventListener("DOMContentLoaded", function() {
const connection = new WebSocket(HOST);
.....
This is the point that the error occurs and this is the caught error that I get:
bubbles
:
false
cancelBubble
:
false
cancelable
:
false
composed
:
false
currentTarget
:
WebSocket
defaultPrevented
:
false
eventPhase
:
0
isTrusted
:
true
path
:
Array(0)
returnValue
:
true
srcElement
:
WebSocket
target
:
WebSocket
timeStamp
:
213.01500000000001
type
:
"error"
__proto__
:
Event
I am not too familiar with server side programming and was trying to understand. I tried looking up this issue, but it seems like a variety of different things can cause this. If you want to see the repository you can see and try it yourself (uses webpack): SlidingWarfare Repo
The confusion starts here:
const server = express();
The express function doesn't really return a server, it returns an application. Commonly, the variable used for this is app, but that's of course nothing more than convention (i.e. not a requirement).
However, it becomes an issue when you pass the app to the WS server:
const wss = new SocketServer({ server });
That's because SocketServer requires an HTTP server instance, which server is not.
Here's a fix, without renaming your variables:
let httpServer = server.listen(PORT, () => console.log(`Listening on ${ PORT }`));
...
const wss = new SocketServer({ server : httpServer });
(because when you call .listen() on the Express instance, it will return an HTTP server instance)
Using the variable naming convention it would be this:
const app = express();
app.use(express.static(path.join(__dirname, 'lib')));
app.use('/assets', express.static(path.join(__dirname, 'assets')));
let server = app.listen(PORT, () => console.log(`Listening on ${ PORT }`));
const wss = new SocketServer({ server });

Is there a way to communicate with WebSocket over SSL from NativeScript app?

Currently I am writing a NS app that will communicate with a WebSocket over SSL. Here is server's code (server.js):
var fs = require('fs');
var cfg = {
port: 8082,
ssl_key: fs.readFileSync('keys/server.key'),
ssl_cert: fs.readFileSync('keys/server.crt'),
ca: fs.readFileSync('keys/ca.crt')
};
var httpServ = require('https');
var WebSocketServer = require('ws').Server;
var app = null;
// dummy request processing
var processRequest = function( req, res ) {
res.writeHead(200);
res.end("All glory to WebSockets!\n");
};
app = httpServ.createServer({
// providing server with SSL key/cert
key: cfg.ssl_key,
cert: cfg.ssl_cert,
ca: cfg.ssl.ca,
passphrase: '1234',
requestCert: true,
rejectUnauthorized: false,
}, processRequest ).listen( cfg.port );
var wss = new WebSocketServer( { server: app } );
wss.on('connection', function(ws) {
console.log("Connected!");
ws.on('message', function(message) {
console.log('received: %s', message);
});
ws.send('something');
});
Server is running well without problem. Below is the client code (wsclient.js):
const WebSocket = require('ws');
const ws = new WebSocket('wss://localhost:8082');
ws.on('open', function open() {
ws.send("dummy");
ws.on('error', function(evt) {
console.log("The socket had an error", evt.error);
});
});
When I ran the client by typing node wsclient.js, it throw the following error:
Error: unable to verify the first certificate
Obviously, the error was caused by not providing the certificate info to the request. But I have no idea how to get this done in my client code. Thanks a lot for any clues or suggestions.
Finally I found the answer:
const WebSocket = require('ws');
const ws = new WebSocket('wss://localhost:8082',{
key: fs.readFileSync('./keys/client.key'),
cert: fs.readFileSync('./keys/client.crt'),
ca: fs.readFileSync('./keys/ca.crt')
});
ws.on('open', function open() {
ws.send("dummy");
ws.on('error', function(evt) {
console.log("The socket had an error", evt.error);
});
});
Now it works!

Loopback IO OAuth not working

I am trying to get a https loopback server up and running protected by OAuth. I am using the loopback gateway sample project as a reference. But for some reason I can't get the OAuth piece to work. What I mean is, even after adding in the OAuth bits and pieces, the APIs don't seem to be protected. I get a response back even if there is no token in my request. This is what my server.js looks like
var loopback = require('loopback');
var boot = require('loopback-boot');
var https = require('https');
var path = require('path');
var httpsRedirect = require('./middleware/https-redirect');
var site = require('./site');
var sslConfig = require('./ssl-config');
var options = {
key: sslConfig.privateKey,
cert: sslConfig.certificate
};
var app = module.exports = loopback();
// Set up the /favicon.ico
app.middleware('initial', loopback.favicon());
// request pre-processing middleware
app.middleware('initial', loopback.compress());
app.middleware('session', loopback.session({ saveUninitialized: true,
resave: true, secret: 'keyboard cat' }));
// -- Add your pre-processing middleware here --
// boot scripts mount components like REST API
boot(app, __dirname);
// Redirect http requests to https
var httpsPort = app.get('https-port');
app.middleware('routes', httpsRedirect({httpsPort: httpsPort}));
var oauth2 = require('loopback-component-oauth2')(
app, {
// Data source for oAuth2 metadata persistence
dataSource: app.dataSources.pg,
loginPage: '/login', // The login page url
loginPath: '/login' // The login processing url
});
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Set up login/logout forms
app.get('/login', site.loginForm);
app.get('/logout', site.logout);
app.get('/account', site.account);
app.get('/callback', site.callbackPage);
var auth = oauth2.authenticate({session: false, scope: 'demo'});
app.use(['/protected', '/api', '/me', '/_internal'], auth);
app.get('/me', function(req, res) {
// req.authInfo is set using the `info` argument supplied by
// `BearerStrategy`. It is typically used to indicate scope of the token,
// and used in access control checks. For illustrative purposes, this
// example simply returns the scope in the response.
res.json({ 'user_id': req.user.id, name: req.user.username,
accessToken: req.authInfo.accessToken });
});
signupTestUserAndApp();
//var rateLimiting = require('./middleware/rate-limiting');
//app.middleware('routes:after', rateLimiting({limit: 100, interval: 60000}));
//var proxy = require('./middleware/proxy');
//var proxyOptions = require('./middleware/proxy/config.json');
//app.middleware('routes:after', proxy(proxyOptions));
app.middleware('files',
loopback.static(path.join(__dirname, '../client/public')));
app.middleware('files', '/admin',
loopback.static(path.join(__dirname, '../client/admin')));
// Requests that get this far won't be handled
// by any middleware. Convert them into a 404 error
// that will be handled later down the chain.
app.middleware('final', loopback.urlNotFound());
// The ultimate error handler.
app.middleware('final', loopback.errorHandler());
app.start = function(httpOnly) {
if(httpOnly === undefined) {
httpOnly = process.env.HTTP;
}
server = https.createServer(options, app);
server.listen(app.get('port'), function() {
var baseUrl = (httpOnly? 'http://' : 'https://') + app.get('host') + ':' + app.get('port');
app.emit('started', baseUrl);
console.log('LoopBack server listening # %s%s', baseUrl, '/');
});
return server;};
// start the server if `$ node server.js`
if (require.main === module) {
app.start();
}
function signupTestUserAndApp() {
// Create a dummy user and client app
app.models.User.create({username: 'bob',
password: 'secret',
email: 'foo#bar.com'}, function(err, user) {
if (!err) {
console.log('User registered: username=%s password=%s',
user.username, 'secret');
}
// Hack to set the app id to a fixed value so that we don't have to change
// the client settings
app.models.Application.beforeSave = function(next) {
this.id = 123;
this.restApiKey = 'secret';
next();
};
app.models.Application.register(
user.username,
'demo-app',
{
publicKey: sslConfig.certificate
},
function(err, demo) {
if (err) {
console.error(err);
} else {
console.log('Client application registered: id=%s key=%s',
demo.id, demo.restApiKey);
}
}
);
});
}
I don't get any errors when the server starts up. Thoughts?
Got it figured. More information here https://github.com/strongloop/loopback-gateway/issues/17, but basically I had my rest-api middleware not configured right.

Categories

Resources