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'));

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');
    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; =; =;
Get the Session
app.get('/get-session', function(req, res) {    
    sessionData = req.session;
    userDetails.isLogin = sessionData.isLogin; =; =;

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

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

Question: Session is not working with ajax call
When running in browser, session is working fine.
When running with ajax call, session is not working

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