Saurabh Sharma
Saurabh Sharma

Reputation: 804

JWT Token is not setting on Headers in $resource

I am using JWT for User Authorization. I am inserting data in mongodb with Node API. Now I want to insert loggedin User's id in to mongodb along with data.

Angular

//factory for blog insert
app.factory('blogFactory', function($resource, $rootScope){
  return $resource('/api/addblog/:id', {id:'@_id'},{get:{headers:{'authorization':$rootScope.token}}});
});

//controller for add blog

    app.controller('blogpostCtrl', function($rootScope, $scope, blogFactory, $location){

      $scope.addBlog=function(){
          $scope.blogg=new blogFactory($scope.blog); 
          $scope.blogg.$save(function(){ 
            $scope.blog=" ";
              $scope.alert="Blog Successfully Inserted..!!!";
                });
      };
    });

Node api

apiRoutes.post('/addblog', function(req, res){ 
  var tokenx=req.headers.authorization;
  console.log(tokenx);
  var loggedinUser= jwt.decode(tokenx, config.secret);

  var CurrentDate=Date.now(); 
  var newBlog=new blogModel({
    title:req.body.title, 
    description:req.body.description, 
    category:req.body.category,  
    date:CurrentDate,
    by:loggedinUser._id
  });
  newBlog.save(function(err, data){
    if(err){return res.json({success:false, msg:'Blog Not Posted'})}
      else{
        res.json({success:true, msg:'Successfully Posted'});
      }
  });

});

So, I want to know that, Is it the right way to write headers in $resource with angular js. When I execute this code its showing an error Error: No Token Supplied. and in console.log an error is also showing POST http://localhost:3000/api/addblog 500 (Internal Server Error).

Please help.

Upvotes: 0

Views: 887

Answers (2)

abdulbari
abdulbari

Reputation: 6242

Your header must be included in Access-Control-Allow-Headers header in response to the OPTIONS request.

app.use(function(req, res, next) {

  // Website you wish to allow to connect
  res.setHeader('Access-Control-Allow-Origin', '*');

  // 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,authorization');

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

  // Pass to next layer of middleware
  next();
});

Edit

You can see multiple ways to send your request with angular.js

how to set custom headers with a $resource action?

Upvotes: 1

Shankar Gurav
Shankar Gurav

Reputation: 1067

There are may ways you can set authorization token in request, it will be based on use case. here is the answer I wrote, may be helpful to you.

Upvotes: 0

Related Questions