Example #1
0
		httpServer.listen(ConfigServer.port, function () {

			app.use(bodyParser.json());
			app.use(cookieParser());
			app.set('view engine', 'jade');
			app.use(express.static(__dirname + '/http/templates'));
			// app.configure(function() {
			// });
			//routes
			app.get('/', function (req, res) {
				res.sendStatus(403);
			});
			app.use('/cookie', cookieRoutes);

			//we return http server ressource because WebsocketServer need it
			resolv(httpServer);
		});
Example #2
0
  /**
   *
   * Express Middleware
   *
   */
  createExpress() {
    const app = new Express()

    app.use(bodyParser.json())
    app.use(function(req, res, next) {
      res.header('Access-Control-Allow-Origin', '*')
      res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
      next()
    })

    app.get('/ding', function(req, res) {
      log.silly('Server', '%s GET /ding', new Date())
      res.end('dong')
    })

    return app
  }
Example #3
0
  before(function(done) {
    app = new Express();

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));

    app.get('/', function(req, res) {
      res.send({
        message: 'ok'
      });
    });

    app.delete('/', function(req, res) {
      res.send({
        message: 'ok'
      });
    });

    app.post('/', function(req, res) {
      res.send(req.body);
    });

    process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
    var libRoot = path.resolve(__dirname, './lib');

    var options = {
      key: fs.readFileSync(libRoot + '/client-key.pem'),
      cert: fs.readFileSync(libRoot + '/client-cert.pem'),
      requestCert: false,
      rejectUnhauthorized: false
    };

    server = http.createServer(app).listen(port, function(err) {
      if (err) throw err;

      httpsServer = https.createServer(options, app).listen(httpsPort, function(err) {
        if (err) throw err;

        done();
      });
    });


  });
Example #4
0
export default function server(app: express) {
  app.use("/notify", notifHandler({
    handlers: {
      "ship:update": commandHandler,
      "segment:update": commandHandler,
      "segment:delete": commandHandler,
      "user:update": userHandler
    }
  }));
  app.use("/batch", notifHandler({
    handlers: {
      "user:update": userHandler
    }
  }));

  app.all("/sync", (req, res) => {
    res.end("ok");
  });

  app.all("/webhook", webhookHandler);

  app.get("/admin", adminHandler);

  app.post("/fetch-all", fetchAllHandler);

  app.use("/schema/custom_fields", cors(), (req, res) => {
    res.send({
      options: _.get(req, "hull.ship.private_settings.traits_mapping", []).map(name => {
        return {
          label: name,
          value: name
        };
      })
    });
  });

  return app;
}
Example #5
0
/**
 * Configure server
 */
function createHandler (enhancer) {
  let handler = new Express()

  handler.use(morgan('combined'))
  // Add production middlewares
  if (!config.DEBUG) {
    handler.use(compression())
  }

  // Static files middleware
  handler.use(Express.static(path.join(__dirname, './public/')))

  if (enhancer) {
    handler = enhancer(handler)
  }

  // Main handler
  handler.get('*', (req, res) => {
    const memoryHistory = createMemoryHistory(req.url)
    const store = configureStore(memoryHistory)
    const history = syncHistoryWithStore(memoryHistory, store)

    match({ history, routes, location: req.url }, (error, redirectLocation, renderProps) => {
      if (error) {
        res.status(500).send(error.message)
      } else if (redirectLocation) {
        res.redirect(302, redirectLocation.pathname + redirectLocation.search)
      } else if (renderProps) {
        res.send(render(store, renderProps))
      } else {
        res.status(404).send('Not Found')
      }
    })
  })

  return handler
}
Example #6
0
var userOptions = {};
if(process.env.OPENSHIFT_DATA_DIR) {
	userOptions.dataDirectory = process.env.OPENSHIFT_DATA_DIR;
}

var user = new SteamUser(null, userOptions);
user.logOn(); // Log onto Steam anonymously

var app = new Express();
app.listen(PORT, IP);

app.use(cors);
app.use(checkLogOn);

app.get('/', function(req, res) {
	res.redirect("https://github.com/DoctorMcKay/steam-pics-api");
});

app.get('/changes/:changenumber', function(req, res) {
	var changenumber = parseInt(req.params.changenumber, 10);
	if(isNaN(changenumber)) {
		sendJsonResponse(req, res, "Invalid changenumber", 400);
		return;
	}
	
	var timedOut = false;
	
	var timeout = setTimeout(function() {
		sendJsonResponse(req, res, "Steam request timed out", 504);
		timedOut = true;
	}, 15000); // 15 seconds
Example #7
0
 app.listen(app.get('port'), function () {
     logger.info('Express server listening on port ', app.get('port'));
 });
Example #8
0
require('./polyfill');

var express = require('express');
var app = new express();
var parser = require('body-parser');

app.get('/', rootGet)
  .use(express.static(__dirname + '/../.tmp'))
  .listen(7777);

function rootGet(req, res) {
  res.render('../app/index.ejs', {});
}

app.use(parser.json());
app.use(parser.urlencoded({
  extended: false
}));

require('./routes/items')(app);
Example #9
0
var path = require('path');
var express = require('express');
var favicon = require('serve-favicon');

var app = new express();
var port = 8888;


app.use(express.static(path.join(__dirname, 'dist')));
app.use(favicon(path.join(__dirname, 'dist', 'favicon.ico')));


app.get("/*", function(req, res) {
  return res.sendFile(__dirname + '/dist/index.html')
})

app.listen(port, function(err) {
  if (err) {
    console.error(err)
  } else {
    console.info("==> 🌎  Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port)
  }
})
Example #10
0
var webpack = require('webpack')
var webpackDevMiddleware = require('webpack-dev-middleware')
var webpackHotMiddleware = require('webpack-hot-middleware')
var config = require('./webpack.config')

var express = require('express');
var app = new express()

var port = 3000

var compiler = webpack(config)
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }))
app.use(webpackHotMiddleware(compiler))
app.use(express.static(__dirname + '/public'));

app.listen(port, function(error) {
  if (error) {
    console.error(error)
  } else {
    console.info("==> Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port)
  }
})

app.get("/", function(req, res) {
  res.sendFile(__dirname + '/index.html')
})
"use strict";
console.log("Running webapp...");

let Express = require('express');
let app = new Express();
let port = process.env.PORT || 80;
app.use(require('body-parser').urlencoded());
app.use(require('body-parser').json());

app.use(Express.static('./app'));
app.get('/messages',(req,res)=>{
	res.status(200).json(require('./messages.json'));
});
app.listen(port,()=>{
	//console.log(`Running webhook listener...`);
	console.log(`App listening on port ${port}`);
}) ;
Example #12
0
"use strict";
const express = require('express');

let app = new express();
app.use(express.static(__dirname + '/public'));


app.get('/hi', (req,res)=>{
	res.send('Привет');

});

app.get('*', (req, res)=>{
	res.sendFile(__dirname + '/public/index.html');
});

app.listen(3000, ()=>{
	console.log('Star server on port 3000');
});
Example #13
0
var webpack = require('webpack')
var webpackDevMiddleware = require('webpack-dev-middleware')
var webpackHotMiddleware = require('webpack-hot-middleware')
var config = require('./webpack.development.config')
var path = require('path')
var Express = require('express')

var app = new Express()
var port = 9000

var compiler = webpack(config)
app.use(webpackDevMiddleware(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath,
  historyApiFallback: true
}))
app.use(webpackHotMiddleware(compiler))

app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, '/index.html'))
})

app.listen(port, function (error) {
  if (error) {
    console.error(error)
  } else {
    console.info('==> Listening on port %s. Open up http://localhost:%s/ in your browser.', port, port)
  }
})
Example #14
0
var express = require('express');

var app = new express();

app.get('/cheer.txt',function(req,res){
  res.end('You are awesome');  
});

app.get('/jeer.txt',function(req,res){
  res.end('What are you doing');  
});

app.listen(8080,function(){
    console.log('Live now!!!!');
});
Example #15
0
app.use('/api', projects);
// this is supposed to be TEMPORARY -- until i figure out
// isomorphic rendering
app.use('/', serverRoutes);

// configure passport
require('./config/passport');
// const passportConfig = require('./config/passport');

// Connect to MongoDB
// mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI);
mongoose.connect(serverConfig.mongoURL);
mongoose.connection.on('error', () => {
  console.error('MongoDB Connection Error. Please make sure that MongoDB is running.');
  process.exit(1);
});

app.get('/', (req, res) => {
  res.sendFile(path.resolve(`${__dirname}/../index.html`));
});

// start app
app.listen(serverConfig.port, (error) => {
  if (!error) {
    console.log(`p5js web editor is running on port: ${serverConfig.port}!`); // eslint-disable-line
  }
});

export default app;

Example #16
0
// }}}

// {{{ App Specific Constants
var STRUCTURE_KEY          = 'Description';
var BASIC_COMMAND_CATEGORY = '$Base';
var CUSTOM_CATEGORY        = 'VANL';
var TTS_TYPE               = 'Say';
var SILENT_TTS             = '$SILENT';
var BASE_PROFILE           = __dirname + '/public/BASE_PROFILE.vap';
var COMPILED_PROFILE       = __dirname + '/public/COMPILED_PROFILE.vap';

// }}}

app.get('/', function(req, res) {
    res.render('home');
});

app.post('/edit', function(req, res) {
    req.pipe(req.busboy);

    req.busboy.on('file', function(fieldname, file, filename) {
        var val = "";
        file.on('data', function(data) {
            val = val + data;
        });
        file.on('end', function() {
            xml2js.parseString(val, function(err, result) {
                var basic_commands = {};
                result.Profile.Commands[0].Command =_.filter(
                    result.Profile.Commands[0].Command,
const webpack = require('webpack');
const path = require('path');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const config = require('./webpack.config');
const express = require('express');

const app = new express();
const port = 3000;

const compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
app.use(webpackHotMiddleware(compiler));

app.use('/static', express.static('static'));

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, '/index.html'));
});

app.listen(port, (error) => {
  if (error) {
    console.error(error);
  } else {
    console.info(`==> 🌎  Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`);
  }
});
Example #18
0
    var server = net.createServer({pauseOnConnect: true}, function (connection) {
        console.log('A new connection on ' + os.hostname());
        // We received a connection and need to pass it to the appropriate
        // worker. Get the worker for this connection's source IP and pass
        // it the connection.
        var remoteAddress = connection.remoteAddress.replace(/^.*:/, '');
        var worker = workers[worker_index(remoteAddress, num_processes)];
        worker.send('sticky-session:connection', connection);
    }).listen(port);
} else {
    // Note we don't use a port here because the master listens on it for us.
    var app = new express();

    // Here you might use middleware, attach routes, etc.
    app.get('/', function (req, res) {
        res.sendFile(__dirname + '/index.html');
    });

    // Don't expose our internal server to the outside.
    var server = app.listen(0, 'localhost'),
        io = sio(server);

    // Tell Socket.IO to use the redis adapter. By default, the redis
    // server is assumed to be on localhost:6379. You don't have to
    // specify them explicitly unless you want to change them.
    io.adapter(sio_redis({host: 'localhost', port: 6379}));

    // Here you might use Socket.IO middleware for authorization etc.
    io.on('connection', function (socket) {
        socket.on('chat message', function (msg) {
            io.emit('chat message', msg);
Example #19
0
var express = require('express');

var app = new express();

var parser = require('body-parser');

app.get('/',function(req,res) {
  res.render('./../app/index.ejs',{});
})
.use(express.static(__dirname +'/../.tmp'))
.listen(7777);

app.use(parser.json());
app.use(parser.urlencoded({extended:false}));

// require('./routes/items.js')(app);
/* global require, process, __dirname, console */
require("newrelic");
var Express = require("express"),
    newrelic = require("newrelic"),
    compression = require("compression"),
    serveStatic = require('serve-static'),
    pug = require("pug"),
    port = Number(process.env.PORT || 5000),
    staticAssetsUrl = process.env.STATIC_ASSETS_URL || ".",
    directory = process.env.NODE_ENV === "production" ? "/build" : "/public",
    server = new Express();

server.locals.newrelic = newrelic;

server.use(compression());
// This is required to serve legacy copied email signatures
server.use(serveStatic(__dirname + "/public"));

server.set("views", __dirname + directory + "/pug");
server.engine("pug", pug.__express);

server.get("/", function (request, response) {
    "use strict";
    response.set("Cache-Control", "no-cache");
    response.render("index.pug", {staticAssetsUrl: staticAssetsUrl});
});

server.listen(port);
console.log("Server listening on port " + port);
Example #21
0
var app = new express();

app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, "public")));

app.listen(1333, function(){
    console.log('Server started');
});

app.get('/api', function (req, res) {
    res.send('API is running');
});

app.listen(1337, function(){
    log.info('Express server listening on port 1337');
});

app.use(function(req, res, next){
    res.status(404);
    log.debug('Not found URL: %s',req.url);
    res.send({ error: 'Not found' });
    return;
});

app.use(function(err, req, res, next){
    res.status(err.status || 500);
  it('访问/cas/serviceValidate, 带ticket, ticket合法, 有pgtUrl, 先调pgtUrl, 传过去pgtIou和pgtId, 然后响应成功xml, 带userId和pgtIou', function(done) {
    var store = {};

    // cas server
    var casHost = 'http://localhost';
    var casPort = 3004;
    var app = new Express();
    casServerFactory(app);
    server = http.createServer(app);

    // cas client
    var localHost = 'http://localhost';
    var localPort = 3002;
    var appLocal = new Express();
    var serverLocal = http.createServer(appLocal);
    appLocal.get('/cas/proxyCallback', function(req, res) {
      if (req.query) {
        expect(req.query.pgtIou).to.not.be.empty;
        expect(req.query.pgtId).to.not.be.empty;
        store[req.query.pgtIou] = req.query.pgtId;
        res.send('ok');
      } else {
        res.sendStatus(400);
      }
    });

    serverLocal.listen(3002, function(err) {
      if (err) throw err;

      server.listen(3004, function(err) {
        if (err) throw err;

        var service = localHost + ':' + localPort + '/cas/validate';
        var pgtUrl = localHost + ':' + localPort + '/cas/proxyCallback';

        utils.getRequest('http://localhost:3004/cas/login?service=' + encodeURIComponent(service), function(err, response) {
          if (err) throw err;

          var uri = url.parse(response.header.location, true);

          var ticket = uri.query.ticket;

          expect(ticket).to.not.be.empty;

          utils.getRequest('http://localhost:3004/cas/serviceValidate?service=' + encodeURIComponent(service) + '&ticket=' + ticket + '&pgtUrl=' + encodeURIComponent(pgtUrl), function(err, response) {
            if (err) throw err;

            expect(response.status).to.equal(200);

            var parseCasResponse = validate.__get__('parseCasResponse');

            parseCasResponse(response.body, logger, function(err, info) {
              if (err) throw err;

              expect(info.user).to.not.be.empty;
              expect(info.proxyGrantingTicket).to.not.be.empty;

              expect(store[info.proxyGrantingTicket]).to.not.be.empty;

              server.close(function(err) {
                if (err) throw err;

                serverLocal.close(function(err) {
                  if (err) throw err;
                  done();
                });
              });
            });
          });
        });
      });
    });
  });
Example #23
0
    fs = require('fs');
    jsend = require('jsend');
    request = require('request');

var app = new express();
app.use(bodyParser.json());
app.use(cors());

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use('/uploads', express.static(__dirname + '/uploads'));
app.use('/public', express.static(__dirname + '/public'));

app.get('/', function(req, res){
  res.render('index');
});

app.get('/api/', function(req, res){
  res.render('index');
});

var baseURL = '<insert your server here>/uploads';
var specialURL = '<insert special server here>';

// index.js continued
app.post('/', multer({ dest: './uploads/'}).single('imgFile'), function(req,res){
	// This is the form fields
        console.log(req.body);
        console.log(req.file);
        console.log(req.file.path);
function generate (array, config) {

	var app = new express();
	app.restifyConfig = {};

	if (config) {
		
		app.restifyConfig.ID = config.ID || 'id';
		app.restifyConfig.prefix = config.prefix || '';
		app.restifyConfig.sufix = config.sufix || '';
		app.restifyConfig.logRequest = config.logRequest || false;
		app.restifyConfig.restName = config.restName || 'name';

	} else {

		app.restifyConfig = createBasicConfiguration();

	}

	app.restifyConfig.array = array;


	if (app.restifyConfig.logRequest) {

		app.use(function (req, res, next) {
			
			console.log('%s - %s', req.method, req.url);
			next();

		});

	}

	app.use(bodyParser.urlencoded({ extended : false }));
	app.use(bodyParser.json());

	var url = '/' + ((app.restifyConfig.prefix != '') ? app.restifyConfig.prefix + '/' : '');
	url += app.restifyConfig.restName;
	url += ((app.restifyConfig.sufix != '') ? app.restifyConfig.sufix : '');

	console.log('Publishing GET - %s...', url);
	app.get(url, function (req, res) {
		res.json(app.restifyConfig.array);
	});

	console.log('Publishing POST - %s...', url);
	app.post(url, function (req, res) {
	
		var findInfo = {};
		findInfo[app.restifyConfig.ID] = req.body[app.restifyConfig.ID];

		var index = _.findIndex(app.restifyConfig.array, findInfo);

		if (index < 0) {

			app.restifyConfig.array.push(req.body);
			res.json(req.body);

		} else {

			res.status(500).json({ err : 'ID already exists'});
		}	
	});


	url += '/:id';
	console.log('Publishing GET - %s...', url);
	app.get(url, function (req, res) {

		var findInfo = {};
		findInfo[app.restifyConfig.ID] = parseInt(req.params.id);

		var index = _.findIndex(app.restifyConfig.array, findInfo);

		if (index >= 0) {

			res.json(app.restifyConfig.array[index]);

		} else {

			res.status(204).json({ err : 'ID not exists'});
		}

	});

	console.log('Publishing PUT - %s...', url);
	app.put(url, function (req, res) {

		var findInfo = {};
		findInfo[app.restifyConfig.ID] = parseInt(req.params.id);

		var index = _.findIndex(app.restifyConfig.array, findInfo);

		if (index >= 0) {

			app.restifyConfig.array[index] = req.body;
			res.json(app.restifyConfig.array[index]);

		} else {

			res.status(204).json({ err : 'ID not exists'});
		}

	});

	console.log('Publishing DELETE - %s...', url);
	app.delete(url, function (req, res) {

		var findInfo = {};
		findInfo[app.restifyConfig.ID] = parseInt(req.params.id);

		var index = _.findIndex(app.restifyConfig.array, findInfo);

		if (index >= 0) {

			var toRemove = app.restifyConfig.array[index];
			app.restifyConfig.array = _.without(app.restifyConfig.array, toRemove);
			res.json({});

		} else {

			res.status(204).json({ err : 'ID not exists'});
		}

	});

	return app;
		
}
Example #25
0
app.set('view engine', 'jade');
app.engine('jade', require('jade').__express);

app.get('/', function(req, res){

	db.open(function(err, db){
		if(err){
			console.log('open db error!');
		}else{
			db.createCollection('company', function(err , collection){
				if(err){
					console.log('create collection error!');
				}else{
					collection.find().toArray(function(err ,items){
						var length = items.length;

						// for(var i=0;i<length;i++){
						// 	console.log(items[i]);
						// }
						res.render('index', {data:items});

					});
				}
			});
		}
	});

	
});


app.post('/search', function(req, res){
Example #26
0
var express = require('express');
var multer = require('multer'),
    bodyParser = require('body-parser'),
    path = require('path');
var fs = require('fs');
var app = new express();
var connector = require('./Connector.js')
app.use(bodyParser.json());

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');


app.get('/', function(req, res){
    res.render('index');
});
var afterResponse = function(db) {
    console.log('Mongoose afterResponse');
    // any other clean ups
    db.close(function () {
        console.log('Mongoose connection disconnected');
    });

}
app.post('/', multer({ dest: './uploads/'}).single('upl'), function(req,res){

    console.log("req file "+JSON.stringify(req.file));
    connector.connectToMongo('upl',function(err,dbInstance){

        var fileName = req.file.filename;
Example #27
0
var express = require('express');
var config = require('./config.js');
var ParseServer = require('./routes/ParseServer.js');
var fileUploader = require('./routes/fileUploader.js');

var app = new express();

app.use('/parse', ParseServer);
app.post('/upload/:type', fileUploader.upload);
app.get('/file/:type/:name', fileUploader.get);
app.use('*', function(req, resp) {
    resp.send('{"msg":"default page."}');
});

app.listen(config.port, function() {
    console.log('Server is running on ' + config.port + '...');
});
Example #28
0
app.use(function(req, res, next) {
  GLOBAL.navigator = {
    userAgent: req.headers['user-agent']
  }
  next();
});

require('./routes/react-router-render.js')(app);

app.use(cors())
  .use(parser.urlencoded({
    extended: false
  }))
  .use(parser.json())
  .listen(app.get('port'), function() {
    console.log('Node app is running on port', app.get('port'));
  });

// CookieParser should be above session
app.use(cookieParser());

// Express MongoDB session storage
app.use(session({
  saveUninitialized: true,
  resave: true,
  secret: 'nodexeroapp',
  store: new mongoStore({
    mongooseConnection: db.connection
      // collection: 'sessions'
  })
Example #29
0
var express = require('express');
var monk = require('monk');
var db =  monk('localhost:27017/test');
var app = new express();

app.use(express.static(__dirname + '/public'));
app.get('/',function(req,res){
  res.json({});
})
app.get('/collections/:name',function(req,res){
  var collection = db.get(req.params.name);
  collection.find({},{limit:20},function(e,docs){
    res.json(docs);
  })
});
app.listen(3000)
Example #30
0
 .listen(app.get('port'), function() {
   console.log('Node app is running on port', app.get('port'));
 });