Showing posts with label Nodejs. Show all posts
Showing posts with label Nodejs. Show all posts

Monday, 25 January 2016

Nodejs working with JWT (JSON Web Token)

npm install jsonwebtoken

var jwt = require('jsonwebtoken');

var auth = {
    id : id,
    name : 'moin',
    email : 'mastermoin409@gmail.com',


var token = jwt.sign({ authToken: auth }, 'shhh.....', {expiresIn : 1800});


'shhh.....' is private key or secret key of your application, it is normally string

1800 is  token expiry time

More about API : https://github.com/auth0/node-jsonwebtoken
        

Expressjs Module for Returning Random 6 digit number


var express = require('express');

module.exports = {
  getToken: function() {
    return Math.round(Math.random()*100000);
  },
};

Rest API example by Express JS

Application File

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

var routerObject = require('router file path'); //routes are defined here

var app = express(); //Create the Express app

app.listen(8000);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.use('/api', routerObject); //This is our route middleware

module.exports = app;

router file 

var express = require('express');
var router = express.Router();

router.get('/sample', function (request, response) {
    response.json({response:'hello world'});
});


module.exports = router;


Call API As

http://localhost:8000/api/routerObject/sample



Enable CROS origin NODEJS and EXPRESSJS

Add this chunk to app.js

http://code2run.blogspot.ca/2016/01/rest-api-example-by-express-js.html


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();
});

you can replace * with specific domain when your application in turn to production mode

e.g. enable cros request for domain - mastermoin.com 

res.header("Access-Control-Allow-Origin", "mastermoin.com");

* is only recommended for development purpose.