首页 文章

JWT Token没有在$ resource中设置Headers

提问于
浏览
0

我正在使用JWT进行用户授权 . 我正在使用Node API在mongodb中插入数据 . 现在我想将登录用户的id与数据一起插入mongodb .

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

});

所以,我想知道,是否在 $resource 中使用角度js编写 headers 是正确的方法 . 当我执行此代码时,它显示错误 Error: No Token Supplied . 在 console.log 中,错误也显示 POST http://localhost:3000/api/addblog 500 (Internal Server Error) .

请帮忙 .

2 回答

  • 1

    您的标头必须包含在Access-Control-Allow-Headers标头中以响应OPTIONS请求 .

    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

    您可以通过 angular.js 查看多种发送请求的方式

    how to set custom headers with a $resource action?

  • 0

    有些方法可以在请求中设置授权令牌,它将基于用例 . 这是answer我写的,可能对你有所帮助 .

相关问题