【问题标题】:JWT Token is not setting on Headers in $resourceJWT 令牌未在 $resource 中的标头上设置
【发布时间】:2017-02-07 07:00:48
【问题描述】:

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

角度

//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..!!!";
                });
      };
    });

节点接口

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

});

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

请帮忙。

【问题讨论】:

  • 你在req.headers.authorization中获得价值了吗?
  • 没有。它的undefined
  • 在发送过程中你得到$rootScope.token这个值?
  • 你能显示你的主服务器文件吗?
  • 是的$rootScope.token有令牌

标签: javascript angularjs node.js jwt


【解决方案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();
});

编辑

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

how to set custom headers with a $resource action?

【讨论】:

  • 你试过了吗@nitish 回答stackoverflow.com/questions/18924217/…
  • 是的....@nitish 的答案正在工作...现在console.log(req.headers.authorization); 正在打印token
  • 我在我的答案中添加了这个答案,以便任何人都可以轻松找到它
【解决方案2】:

您可以通过多种方式在请求中设置授权令牌,这将基于用例。 这是我写的answer,可能对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-24
    • 2018-07-08
    • 1970-01-01
    • 2020-07-27
    • 2021-11-28
    • 2020-06-09
    • 1970-01-01
    • 2020-12-17
    相关资源
    最近更新 更多