Thursday, 22 June 2017

Express JS - use res.sendFile - use EJS template - Set and Get Session data

setup of EJS template in Express? Get/Set session in Express? How to setup static path in Express

Question: What is res.sendFile() in NodeJS?
It is a simple way to deliver an HTML file to the client.

Example of sendFile
var express = require('express');
var app = express();

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



Question: How to use EJS in Express?
Install the EJS
npm install ejs --save  

Set the Engine as EJS in node server
app.set('view engine', 'ejs');  

render file from node server
app.get('/', function(req, res) {  
  res.render('index', { title: 'The index page!' })
});

Use the parameter in File
<%= title %>



Question: How to Get/Set session in Express?
install session
npm instal express-session --save
Initiaization the session
var session = require('express-session');
app.use(session({
    secret: 'SECRETKEY',
    name: 'SESSION NAME',
    proxy: true,
    resave: true,
    saveUninitialized: true
}));
Set the Session
var sessionData
app.get('/set-the-session', function(req, res) {    
    sessionData = req.session;
    var userDetails = {}    

    //set the session
    sessionData.isLogin = 1;
    sessionData.name = req.body.name;
    sessionData.email = req.body.email;
});
Get the Session
app.get('/get-session', function(req, res) {    
    sessionData = req.session;
    userDetails.isLogin = sessionData.isLogin;
    userDetails.name = sessionData.name;
    userDetails.email = sessionData.email;
    res.send(userDetails);    
});


Question: How to setup static path in Express?
var express = require('express');
var app = express();
app.use(express.static('public'))

create file in : images/kitten.jpg, Now you can access
http://localhost:3000/images/kitten.jpg


Question: Session is not working with ajax call
Explanation
URL: http://127.0.0.1:8080/getphotoaccess?uid=7177
When running in browser, session is working fine.
When running with ajax call, session is not working

Solution
You need to add xhrFields: {: true},in ajax request.
For Example:
$.ajax({
    type: "GET",
    url: "getphotoaccess?uid=7177",            
    dataType: "json",    
    xhrFields: {
            withCredentials: true
       },            
    success: function(resData){

    }
});