Skip to content

API Create and host the server

Romain Francois edited this page Dec 19, 2016 · 3 revisions

Prepare and launch the server

Packages

To start the server we need to add some packages into our server files. For Quickshare, we will add the packages described below:

var express 		= require('express');
var app     		= express();
var mongoose		= require('mongoose');
var morgan			= require('morgan');
var bodyParser		= require('body-parser');
var methodOverride 	= require('method-override');
var http			= require('http').Server(app);
var fs 				= require('fs');
var io 				= require('socket.io')(http);
var cors			= require('cors');
var cookieParser 	= require('cookie-parser');
var cron 			= require('node-cron');

These packages are required to make the server working.
Express will help us to serve what we want easily, it is the core of our API.
Mongoose will help us to establish a contact with our mongoDB.
Morgan logs every requests to the API. Logs are very important, first to detect bugs and then to learn about the usage of the application.
Bodyparser handles the informations from POST requests for express 4.
Method-override simulates DELETE and PUT requests for express 4.
Http (or Https) is used to create the server.
Fs is a library to open easily and simply files.
Io allows us to establish a virtual link between the users and the API. We can notice users of every change in real time.
Cors is a library to handle CORS requests (Cross Origin Ressources Sharing).
CookieParser is a middleware used to handle cookies and signed cookies for Express 4.
Cron is a library to create CRON tasks.

Note that the order and requires may change if you want to use HTTPS server. In order to do this please refer to the serverHTTPS.js file.

We also require some files we created, as the config.js file, or the routes.js file:

var config 	 		= require('./config/config');
var router  		= require('./app/routes');	
var Cleaner			= require('./app/cleaner');

The config file contains every options we need, the database credentials, secret phrase for cookieparser, JWT, etc.. The router file contains all the available routes the API can handle, and the behaviours linked with. The cleaner file is a little script used with a CRON task to clean the database of old and expired information.


Configuration

Before serving, we have to define some options and tell our app which packages to use:

var corsOptions = {
	origin: function(origin, callback){
	    var originIsWhitelisted = config.whitelist.indexOf(origin) !== -1;
	    callback(originIsWhitelisted ? null : 'Bad Request', originIsWhitelisted);
	},
	optionsSuccessStatus: 200,
	credentials: true
};

Credentials are activated, you can set the domains whitelist for yours websites.

var port = process.env.PORT || 80;

The port is 80 for a HTTP server, 443 for a HTTPS server.

mongoose.connect(config.database, function (err) {
	if(err) { 
		throw err; 
		console.log("Database connection Error");
	}
});

Here we set the connection to the mongo database.

app.use(cookieParser(config.cookieSecret));
app.use(express.static(__dirname + '/public'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());
app.set('socketio', io);

Basically we tell our app which middlewares to use. The last line set the variable 'socketio' to use it everywhere in the project.

Note: We set the cors middleware after the robot.txt route.


Routes

Now the app is ready, we need to set the different routes:

app.use('/robots.txt', function(req,res) {
	console.log('robot: '+req.hostname +', IP: '+req.ip);
	res.status(200).sendFile(__dirname+'/robots.txt');
});

This route is for web robots. By default, the robots.txt file denies all scan requests.

app.use(cors(corsOptions));
app.options('*', cors());

Then we set the cors middleware and applies it to all the following routes.

app.use('/api', router);
app.use('*', function(req, res) {
	console.log('request host: '+req.hostname +' , IP: '+req.ip);
    res.status(404).sendFile(__dirname+'/public/404.html');
});

The first line redirect all requests to our router. The second one handle default route (404 not found).


Sockets and CRON

Here we set the socket and the cron task to clean old information.

io.on('connection', function(socket) {
console.log('a user connected');
});

When a user will connect to the api the server will be noticed.

cron.schedule('30 * * * *', function(){
console.log('//////// Start Cleaning.. ////////');
Cleaner.deleteOldInfo();
});

This CRON task is executed every 30 min.


Finally, Start the server

http.listen(port, function(){
	console.log('Server listening on port' + port);
});

This part may change for the HTTPS server, please take a look the serverHTTPS.js file

Clone this wiki locally