Showing posts with label ExpressJs. Show all posts
Showing posts with label ExpressJs. Show all posts

Tuesday 12 September 2017

How to create an HTTPS server in Node.js?

How to create an HTTPS server in Node.js?

Question: Run Node with http?
var express = require('express');
var app = express();

//Include modules
var http = require('http').Server(app);
var io = require('socket.io')(http);


http.listen('8082', function() {
    console.log('http listening on *:8082');
});

You can run as http://localhost:8082


Question: What certificate you require for https?
  1. server.key
  2. server.crt
  3. Create a folder public/cert at root of your project and add above 2 files.



Question: Run Node with https?
var express = require('express');
var app = express();

//Include modules

var https = require('https');
fs = require('fs');


var privateKey = fs.readFileSync('public/cert/server.key', 'utf8');
var certificate = fs.readFileSync('public/cert/server.crt', 'utf8');
var credentials = {key: privateKey, cert: certificate};
var httpsServer = https.createServer(credentials, app);
var io = require('socket.io')(httpsServer);

httpsServer.listen('8083', function() {
    console.log('https listening on *:8083');
});
 

You can run as https://localhost:8083



Thursday 13 July 2017

Express JS Interview Questions and Answer for 1 Year Experienced

Express JS Interview Questions and Answer for 1 Year Experienced

Question: What Are Core Features Of Express Framework?
  1. Allows to set up middlewares to respond to HTTP Requests.
  2. Defines a routing.
  3. Dynamically render HTML Pages



Question: Why I Should Use Express Js?
It is light-weight server side web application framework which work on node.js platform.


Question: How to get The full Url In Express?
var port = req.app.settings.port || cfg.port;
res.locals.requested_url = req.protocol + '://' + req.host  + ':'+port + req.path;



Question: How to download a file?
app.get('/download', function(req, res){
  var file = __dirname + '/myfile/download.txt';
  res.download(file); 
});



Question: How To enable debugging In Express App?
In windows
set DEBUG=express:* & node index.js

In Linux
DEBUG=express:* node index.js


Question: How to render plain Html?
res.sendFile();
res.render();


Question: How to use handle get request in express Js?
var app = require('express')();
var http = require('http').Server(app);

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

http.listen('8080', function() {
    console.log('listening on *:8080');
});



Question: How to receive get parameter in Express Js?
app.get('/listing', function (req, res) {   
    console.log(req.query);   //Receive get data
});



Question: How to receive post parameter in express Js?
app.post('/listing', function (req, res) {   
    console.log(req.body);   //Receive post data
});



Question: What is Callback in node.js?
Callback function is used in node.js to deal with multiple requests made to the server. Node is single thread based application and works on the behalf of events.


Question: How to send Ajax call in NodeJS?
Install the request
npm install request

request = require('request');
request( "http://exmaple.com:8081:/users/login/?username=testing@no-spam.ws&password=73278342", function(err, res, body) {                    
          console.log(res.console);          
      });



Question: How to get cookies in expressJs?
npm install cookie-parser
var express = require('express');
var app = express();

var cookieParser = require('cookie-parser');
app.use(cookieParser());

app.get('/listing', function (req, res) {   
    console.log(req.cookies);    
});



Question: What are different methods in REST API?
  1. GET : Used to read.
  2. POST: Used to update.
  3. PUT: Used to create.
  4. DELETE: Used to delete



Question: List out some REPL commands in Node.js?
  1. Ctrl + c - For terminating the current command.
  2. Ctrl + c twice – For terminating REPL.
  3. Ctrl + d - For terminating REPL.
  4. Tab Keys - list of all the current commands.
  5. .break - exit from multiline expression.
  6. .save with filename - save REPL session to a file.



Question: How you can update NPM to new version in Node.js?
sudo npm install npm -g



Question: What do you mean by "Callback hell"?
"Callback hell" is referred to heavily nested callbacks which has become unreadable.


Question: What are "Streams" in Node.JS?
Streams are objects which will let you read the data from source and write data to destination as a continuous process.


Question: What you mean by chaining in Node.JS?
It's a mechanism in which output of one stream will be connected to another stream and thus creating a chain of multiple stream operations.


Question: What is the use of method – spawn()?
This method is used to launch a new process.
child_process.spawn(command[, args][, options])



Tuesday 11 July 2017

Express JS Interview Questions and Answer for experienced

Express JS Interview Questions and Answer for experienced

Question: What is meaning of app.get(*) in express js?
app.get(*) means that for any GET request not already handled yet, will come in this route.
Note: this must be at the end of all route handling (Last route).

See example below:
//Login route
app.get('/login', function(req,res){ /*Login code */ });

//Register route
app.get('/register', function(req,res){/*Register code */});

//Route which is not handled yet
app.get('*', function(req, res, next) {
  var err = new Error();
  err.status = 404;
  next(err);
}

As we know, last route is for not found route, So in this we have set the status 404.
and pass the error object to the next.
When we call next() without parameter, then it run next middleware.
When we call next() with parameter, then it run differently.


Question: What is use of next() in express JS?
next is an argument provided by Express.js as a way to "pass along" control to the next middleware (or route).


Question: What is Middleware?
Middleware are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle.
The next middleware function is commonly denoted by a variable named next.


Question: What are benefits of Middleware?
  1. Execute any code.
  2. Make changes to the request and the response objects.
  3. End the request-response cycle.
  4. Call the next middleware function in the stack.



Question: What are different Middleware?
  1. Application-level middleware
    app.use(function (req, res, next) {
      console.log('Time:', Date.now())
      next()
    })
  2. Router-level middleware
  3. Error-handling middleware
  4. Built-in middleware
  5. Third-party middleware



Question: How to setup log4js?
Install log4js
npm install log4js

Include log4js
//include the log4js file
var log4js = require('log4js');

Configure log4js
//Configure the log4js
log4js.configure({
  appenders: { 
      display: { type: 'stdout' },
      file: { type: 'file', filename: './data/chat_logs.log' }
  
    },
  categories: { 
      display: { appenders: ['display'], level: 'debug' },      
      file: { appenders: ['file'], level: 'debug' },
      default: { appenders: ['display'], level: 'debug' }
      
  }
});

Display log4js in console
var Logger = log4js.getLogger('display'); 

Logger.trace('this is message1');
Logger.info('this is message2');
Logger.warn('this is message3');
Logger.error('this is message4');
Logger.debug('this is message5');
All the data will display in console


Question: How to store the logs in file?
var Logger = log4js.getLogger('file'); 

Logger.trace('this is message1');
Logger.info('this is message2');
Logger.warn('this is message3');
Logger.error('this is message4');
Logger.debug('this is message5');




Thursday 6 July 2017

Node Js Interview Questions and answer for Experienced

Node Js Interview Questions and answer for Experienced

Question: What is objectId in MongoDB?
It is 12 byte object consist of following
  1. a 4-byte value representing the seconds since the Unix epoch
  2. a 3-byte machine identifier
  3. a 2-byte process id
  4. a 3-byte counter, starting with a random value.



Question: How to get timestamp from objectId?
ObjectId.getTimestamp();



Question: What is difference between npm install vs npm update?
npm install:
1. installs all modules that are listed on package.json file and their dependencies.
2. module without version mention in package.json, npm install will be ignore if already installed.

npm update:
1. updates all packages in the node_modules directory and their dependencies.
2. module without version mention in package.json, will update to latest version (If not then installed the latest version).


Question: How to set npm start with start the application?
  1. Open package.json which is located on root.
  2. Add following code in package.json (If not added)
      "scripts": {
        "start": "node index.js"
      }
    

    Please repace "index.js" with your application file.
  3. Now, you can run npm start from command console.



Question: How to destroy the session in node?
You can use req.session.destroy(), See Exampe below:
exports.logout = function(req, res) {        
    req.session.destroy();
    res.send({logout:1});
}



Question: How to redirect to 404 errors page in ExpressJS?
After difining all the URL route, add the following code
app.use(function(req, res, next) {
    res.status(404).json({errorCode: 404, errorMsg: "route not found"});
});

When someone trying to access not available pages, it will show 404 error code.


Question: What is CORS?
Cross Origin Resource Sharing.


Question: What use use of CORS?
Suppose your are website is at mywebiste.com and want to access the javascript/API which is on mywebiste2.com. You can't access the data/api from mywebiste2.com unless they allow you. This is known as Cross Origin Resource Sharing.


Question: How we can achieve CORS?
Add the following code in your node application, it will allow everyone to access your code. In Access-Control-Allow-Origin, you can specify the domain name.
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();
});



Question: What do you mean by Asynchronous API?
All APIs of Node.js library are aynchronous, means all are non-blocking.


Question: What is package.json?
package.json is present in the root directory of any Node application/module and is used to define the properties of a package.


Question: What is Piping in Node?
Piping is a mechanism to connect output of one stream to input of another stream. It means get data from one stream and to pass output of that stream to another stream and there is no limit to piping operations.


Question: What is Callback in node.js?
Callback function is used in node.js to deal with multiple requests made to the server. Node is single thread based application and works on the behalf of events.


Monday 3 July 2017

Express Js routing example - GET/POST/PUT

Express JS Routing - Understanding GET/POST/PUT with parameter

Question: Give example of express JS working with Node?
var express = require('express');
var app = express();

var bodyParser = require('body-parser')
app.use(bodyParser.json());  
app.use(bodyParser.urlencoded({
    extended: true
}));

app.get('/', function(req, res){
  res.send('id: ' + req.query.id);  
});
app.listen(3000);



Question: What is use of body-parser?
It is middleware in nodeJS.
body-parser is used to parse incoming request bodies, available under the req.body property.



Example-1: URL / with Get Method.
app.get('/', function (req, res) {
  res.send('Hello, this is Home page.')
})



Example-2: URL /about with Get Method.
app.get('/about', function (req, res) {
  res.send('You have called /about with get method.')
})



Example-3. URL /senddata with POST Method.
app.post('/senddata', function (req, res) {
    //req.body have all the parameter
   console.log(req.body);
  res.send('Hello, Received post data request.')
})



Example-4: Routing with Regex 
app.get('/ab?cd', function (req, res) {
  res.send('ab?cd')
})

This route path will match acd, abcd.


Example-5: Routing with Regex
app.get('/ab+cd', function (req, res) {
  res.send('ab?cd')
})
This route path will match abcd, abbcd, abbbcd, and so on.



Example-6: Routing with dynamic parameter 
app.get('/users/:userId/books/:bookId', function (req, res) {
  console.log(req.params);
   res.send('Received the request for /users/10/book/12222');
});

Request URL: http://localhost:8080/users/10/books/12222


Example-7: Routing with dynamic parameter - Example 2
app.get('/messages/:from-:to', function (req, res) {
  console.log(req.params);
   res.send('Received the request for /messages/10-100');
});

Request URL: http://localhost:8080/messages/10-1000


Question: How to send request with all methods i.e GET/POST/PUT
app.all('/messages/list', function (req, res) {  
   res.send('Work for all type of request');
});



Thursday 29 June 2017

How to upload file/images using nodejs?

How to upload file using nodejs?

I am assuming you already have install NodeJS in your System, Just follow below simple steps


Install below module ?
npm install express
npm install fs
npm install body-parser
npm install multer



HTML Part?
Create a file upload.html and add below code in file.

        <form action="http://127.0.0.1:8081/file_upload" enctype="multipart/form-data" id="uploadForm" method="POST" onsubmit="return uploadForm()">
Upload File: <input name="file" size="50" type="file" />
            <br />
<input type="submit" value="Upload File" />
        </form>




Node JS Code create upload.js file and add below code.
var express = require('express');
var app = express();
var fs = require("fs");

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

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
var upload = multer({ dest: './tmp' });

app.get('/upload.html', function (req, res) {
   res.sendFile( __dirname + "/" + "upload.html" );
})

app.post('/file_upload', upload.single('file'), function (req, res) {
    console.log(req.file);
    
    
   var file = __dirname + "/public/upload/" + req.file.originalname;
   
   
   fs.readFile( req.file.path, function (err, data) {
      fs.writeFile(file, data, function (err) {
         if( err ){
            console.log( err );
            }else{
               response = {
                  message:'File uploaded successfully',
                  filename:req.file.originalname
               };
            }
         console.log( response );
         res.end( JSON.stringify( response ) );
      });
   });
})

var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port
   
   console.log("Example app listening at http://%s:%s", host, port)
})



Question: Following are sample of file object in ?
 { fieldname: 'file',
  originalname: 'Desert.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: './tmp',
  filename: '3570feafa527690b90b972a1bf085bdd',
  path: 'tmp\\3570feafa527690b90b972a1bf085bdd',
  size: 845941 }


Create following empty folder?
/tmp
/public
/public\upload



Now Start the Node project?
node upload.js



Access the Web URL?
http://127.0.0.1:8081/upload.html



Select the File and click on Upload File?
It will show below simiar message
{"message":"File uploaded successfully","filename":"Desert.jpg"}
Question: What port we have used here?
We have used 8081 port, but you can change it by change in upload.js

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){

    }
});




Thursday 8 June 2017

How to Create RESTful APIs in Node Js using Express JS and MongoDB

How to Create RESTful APIs in Node Js using Express JS and MongoDB

Question: What is RESTful APIs?
Full form of REST is Representational State Transfer. It is web standards architecture used to create an API.


Question: What type of request handled by RESTful APIs?
HTTP requests


Question: How to create an API?
  1. Create a folder with name of api in your node project, and  create three folder inside this. i.e controllers, models and routes.
  2. Create 3 empty files in each folder i.e todoListController.js, todoListModel.js and todoListRoutes.js
  3. Now, Folder Structure will be as below:
  4. -api
        --api/controllers/todoListController.js
        --api/models/todoListModel.js
        --api/routes/todoListRoutes.js
  5. Add Following script in each empty file: todoListController.js
    var mongoose = require('mongoose'),
            Task = mongoose.model('Tasks');
    
    /* List all todoList*/
    exports.list_all_tasks = function(req, res) {
        Task.find({}, function(err, task) {
            if (err)
                res.send(err);
            res.json(task);
        });
    };
    
    
    /* List all todoList*/
    exports.create_a_task = function(req, res) {
        var saveData = {}
        saveData.name = req.body.name;
        saveData.status = req.body.status;
        var new_task = new Task(saveData);
        new_task.save(function(err, task) {
            if (err)
                res.send(err);
            res.json(task);
        });    
    };
    
    /* Get a todo list details*/
    exports.read_a_task = function(req, res) {
        Task.findById(req.params.taskId, function(err, task) {
            if (err)
                res.send(err);
            res.json(task);
        });
    };
    
    /* UPdate a toto data*/
    exports.update_a_task = function(req, res) {
        Task.findOneAndUpdate(req.params.taskId, req.body, {new : true}, function(err, task) {
            if (err)
                res.send(err);
            res.json(task);
        });
    };
    
    
    exports.delete_a_task = function(req, res) {
        Task.remove({
            _id: req.params.taskId
        }, function(err, task) {
            if (err)
                res.send(err);
            res.json({message: 'Task successfully deleted'});
        });
    };


    todoListModel.js
    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    
    var TaskSchema = new Schema({
        name: {
            type: String,
            Required: 'Kindly enter the name of the task'
        },
        Created_date: {
            type: Date,
            default: Date.now
        },
        status: {
            type: [{
                    type: String,
                    enum: ['pending', 'ongoing', 'completed']
                }],
            default: ['ongoing']
        }
    });
    
    module.exports = mongoose.model('Tasks', TaskSchema);
    


    todoListRoutes.js
    module.exports = function(app) {
        var todoList = require('../controllers/todoListController');
    
    
        // todoList Routes
        app.route('/tasks')
                .get(todoList.list_all_tasks)
                .post(todoList.create_a_task);
    
    
        app.route('/tasks/:taskId')
                .get(todoList.read_a_task)
                .post(todoList.update_a_task)
                .delete(todoList.delete_a_task);
    }; 


  6. Create a myapp.js empty file in project folder and add following script code.
    var express = require('express'),
    app = express(),
    port = process.env.PORT || 3000,
    mongoose = require('mongoose'),
    Task = require('./api/models/todoListModel'),
    bodyParser = require('body-parser');
    
    mongoose.Promise = global.Promise;
    mongoose.connect('mongodb://localhost/Tododb');
    
    app.use(bodyParser.urlencoded({extended: true}));
    app.use(bodyParser.json());
    
    var routes = require('./api/routes/todoListRoutes');
    routes(app);
    
    app.listen(port);
    console.log('RESTful API server started: ' + port+' PORT');
    
  7. Now you need install following modules
    npm install express
    npm install mongoose
    npm install body-parser
    
  8. Now run following command, to test the APIs
    node myapp.js
    



Question: Provide Create Task API
URL: http://localhost:3000/tasks
Method: POST
Request Data:
{
"name":"I need to go for walk",
"status":"ongoing"
}



Question: Provide List All records API
URL: http://localhost:3000/tasks
Method: POST
Response Data:
[{"_id":"5937ff6a5fc96f1c1492877f","name":"I will go for walk daily.","__v":0,"status":["ongoing"],"Created_date":"2017-06-07T13:28:10.608Z"},{"_id":"593803fb5fc96f1c14928782","name":"Get up early in the morning","__v":0,"status":["ongoing"],"Created_date":"2017-06-07T13:47:39.246Z"}]



Question: Provide Update Records
URL: http://localhost:3000/tasks/5938d8e86d3e500cd8da6a12
Method: POST
Request Data:
{  
  "name": "I goes on walk daily.", 
}



Question: Provide Get Records:
URL: http://localhost:3000/tasks/5938d8e86d3e500cd8da6a12
Method: POST
Response Data:
{"_id":"5938d8e86d3e500cd8da6a12","name":"Arun kumar Gupta","__v":0,"status":["ongoing"],"Created_date":"2017-06-08T04:56:08.156Z"}



Question: Provide Delete Records
URL: http://localhost:3000/tasks/5938d8e86d3e500cd8da6a12
Method: DELETE
Response Data:
{
  "message": "Task successfully deleted"
}



Tuesday 6 June 2017

How to use cookies with expressJS in node.js

How to use cookies with expressJS in node.js

Question: What is cookies in NodeJS?
Cookies is a node.js module for getting and setting HTTP(S) cookies.


Question: How to install cookies?
npm install cookie-parser       



Question: How to setup cookie with expressJS?
var express = require('express');
var cookieParser = require('cookie-parser');

var app = express();
app.use(cookieParser());
     



Question: What are the feature of cookie?
  1. Lazy: Since cookie verification against multiple keys could be expensive, So cookies are verified lazily.
  2. Secure: All cookies are httponly by default and cookies sent over SSL are secure by default.
  3. Unobtrusive: Signed cookies are stored the same way as unsigned cookies, instead of in an obfuscated signing format.
  4. Agnostic: This library is optimized for use with Keygrip, but does not require it.



Question: How to set cookies?
app.get('/set-cook', function(req, res) {
       //Set the cookie
      var c_name='cookie_name';        
      res.cookie(c_name, 'cookie value');
      
      //Send Response
      res.send('cookie value');
});
Note above wll work with expressJs only.
Question: How to get cookies?
app.get('/get-cook', function(req, res) {        
    //Get cookie name
      var cookieValue=req.cookies.cookie_name; 

      //Send Response
      res.send('Cookie name is '+cookieValue);
});
Note above wll work with expressJs only.



Question: How to delete cookies?
app.get('/delete-cook', function(req, res) {        

    //Delete the cookie
     clearCookie(cookie_name);

      //Send Response
      res.send('Cookie name is '+cookieValue);
});
Note above wll work with expressJs only.



Question: How to set expiration time for cookie?
res.cookie(name , 'value', {expire : new Date() + 600}); //10 minutes

res.cookie(name , 'value', {expire : new Date() + 3600}); //1 hour

res.cookie(name , 'value', {expire : new Date() + 18000}); //5 hour



Question: What are HTTP cookies?
HTTP cookies are small pieces of data that are sent from a website and stored in your browser. With use of cookies we maintain the login and track the user activities. Cookies are very valuable to better user experience. Following are the three main use of cookies.
  1. Session management
  2. Personalization
  3. Track the user activites



Question: Why we must use Cookie-Free Domains for static contents?
Cookies are very useful in website. But while access static contents of website like CSS, image and JS then there is no use of cookie. Means while Browser is accessing the static file, Server should send the static content without use of cookie. It will improve the website performance.



Wednesday 22 March 2017

Express js Interview questions and answers

Express js Interview questions and answers

Question: How to install express js in node?
use following command to install express js.
npm install express



Question: How to use express js in node?
use require to include express module.
var app = require('express')();



Question: How to use handle get request in express Js?
/*Include require module*/
var app = require('express')();
var http = require('http').Server(app);

app.get('/', function (req, res) {
   console.log("Got a GET request for the homepage"); //Shown in console
   res.send('This is GET Method for Homepage'); //Display as response
})

/*Start listing 8080 port*/
http.listen('8080', function() {
    console.log('listening on *:8080');
});



Question: How to use handle post request in express Js?
/*Include require module*/
var app = require('express')();
var http = require('http').Server(app);

app.post('/user_list', function (req, res) {
   console.log("Got a POST request for the user_list URL"); //Shown in console
   res.send('This is POST Method for user_list URL');//Display as response
})

/*Start listing 8080 port*/
http.listen('8080', function() {
    console.log('listening on *:8080');
});



Question: How to use handle GET/POST request for same URL expressJs?
/*Include require module*/
var app = require('express')();
var http = require('http').Server(app);

//This is POST Request
app.post('/add_user', function (req, res) {
   console.log("Got a POST request for the add_user URL"); //Shown in console
   res.send('This is POST Method for add_user URL');//Display as response
})

//This is Get Request
app.get('/user_list', function (req, res) {
   console.log("Got a GET request for the user_list URL"); //Shown in console
   res.send('This is GET Method for user_list URL');//Display as response
})

/*Start listing 8080 port*/
http.listen('8080', function() {
    console.log('listening on *:8080');
});



Question: How to use handle GET request for all URL start with ab* ?
app.get('/ab*', function(req, res) {   
   console.log("Got a GET request for /ab*");
   res.send('Page Regex Match');
})
Question: How to send Server call in Node?
Install the "request" module with following command.
npm install request

Include the request module in page, and send the request to server.
request = require('request');
request( "http://exmaple.com:8081:/users/add/?n=test&p=2277585&email=test@gmail.com", function(err, res, body) {                    
          console.log(res);
          console.log(body);
      });




Question: How to post data and get in express Js?
HTML Code

<form action="http://example.com:8081/register" method="GET">
Name: <input name="name" type="text" />  <br />
Email: <input name="email" type="text" />
         Phone: <input name="phone" type="text" />
         <input type="submit" value="Submit" />
      </form>


Express JS Code
app.get('/register', function (req, res) {   
   response = {
      name:req.query.name,
      email:req.query.email
      phone:req.query.phone
   };
   console.log(response);
   res.end(JSON.stringify(response));
})



Question: How to get cookie in Express js?
Install the "cookie-parser" module with following command.
npm install cookie-parser

Include the cookie-parser, in node.
app.get('/', function(req, res) {
   console.log("Cookies: ", req.cookies)
})


Question: How Static Files works in Express js?
Static files are images/videos/css/js etc.
For this, first you need to set the folder path using "express.static" method. See Example
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/', function (req, res) {
   res.send('Hello ');
});
var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port
})



Question: How to upload images in Express js?
HTML Code

<form action="http://example.com:8081/file_upload" enctype="multipart/form-data" method="POST">
<input name="file" size="50" type="file" />         
         <input type="submit" value="Submit" />
      </form>

ExpressJS Code
var fs = require("fs");
var express = require('express');
var app = express();
var fs = require("fs");

app.post('/file_upload', function (req, res) {
   console.log(req.files.file.name);   
   var destinationFile = __dirname + "/images/" + req.files.file.name;
   
   fs.readFile( req.files.file.path, function (err, data) {
      fs.writeFile(destinationFile, data, function (err) {
         if( err ){
            console.log( err );
            }else{
               response = {
                  message:'File uploaded successfully in '+destinationFile,
                  filename:req.files.file.name
               };
            }
         //console.log( response );
         res.end( JSON.stringify( response ) );
      });
   });
})



Question: What are different methods in REST API?
  1. GET : Used to read.
  2. POST: Used to update.
  3. PUT: Used to create.
  4. DELETE: Used to delete



Question: How to setup the images and access them?
Add Following code in my server.js (OR main file).
app.use(express.static('public'))
Now, you can add images in public folder and can access like below:
http://localhost:3000/1.jpg
http://localhost:3000/2.jpg
http://localhost:3000/3.jpg



Question: How to do increment the value by 1?
 User.update({id: 100}, {$inc: { views: 1 }}).limit(1).exec();



Question: How to do decrement the value by 1?
 User.update({id: 100}, {$inc: { views: -1 }}).limit(1).exec();