Skip to content

Instantly share code, notes, and snippets.

@cpoDesign
Created August 21, 2014 09:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cpoDesign/49d938819dd586a0cd2b to your computer and use it in GitHub Desktop.
Save cpoDesign/49d938819dd586a0cd2b to your computer and use it in GitHub Desktop.
Creating node js server with EJS view engine and routing
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title><%- title%></title>
</head>
<body>
<div> <%- title%></div>
</body>
</html>
{
"name": "application-name",
"version": "0.0.1",
"description": "test server",
"author": {
"name": "cpo",
"email": "pavel.svarc@cpodesign.com"
},
"dependencies": {
"express": "^4.8.5",
"underscore": "^1.6.0",
"jade": "^1.5.0",
"ejs": "^1.0.0",
"ejs-locals": "^1.0.2"
}
}
var http = require('http');
var express = require('express');
var _ = require('underscore');
var app = express();
var ejsEngine = require('ejs-locals');
var url = require('url');
// Setup view engine
app.engine('ejs', ejsEngine); // supports master pages (detail)
app.set('view engine','ejs'); // ejs view engine
app.use(function (req, res, next) {
console.log('%s %s', req.method, req.url);
next();
});
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:63342');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
//
//// sending plain html
app.get('*', function(request, response){
var path = url.parse(request.url).pathname;
switch(path){
case '/test':{
response.render('ejs/index', {title:'ejs engine'});
break;
}
default:{
response.writeHead(404);
response.send("opps this doesn't exist - 404");
break;
}
}
});
var server = http.createServer(app);
server.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment