javascript - JWT token 未在 $resource 中的 header 上设置

标签 javascript angularjs node.js jwt

我正在使用 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'});
      }
  });

});

所以,我想知道,用 Angular js 在 $resource 中编写 headers 是否正确。 当我执行此代码时,它显示错误错误:未提供 token 。并且在 console.log 中还显示错误 POST http://localhost:3000/api/addblog 500(内部服务器错误)

请帮忙。

最佳答案

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

编辑

您可以看到使用 angular.js 发送请求的多种方式

how to set custom headers with a $resource action?

关于javascript - JWT token 未在 $resource 中的 header 上设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39762047/

相关文章:

jquery - 如何使 "require(' jquery')"自动加载 webpack 中的许多 jquery 插件/扩展?

javascript - Webpack 将所有 url() 路径更改为同一路径

javascript - Django 静态 js 文件不起作用

javascript - AngularJS ui.bootstrap 模式对话框未显示

javascript - 我在 IE8 中不断收到 Object.create 错误

node.js - 在安全帽上部署契约(Contract)或创建 NFT 时出现错误 : ProviderError: invalid sender

javascript - 为什么添加参数后功能会停止

javascript - 在 Node 中模拟一个使用链式函数调用的 Node 模块

javascript - 使用 Hapi.js 和 Angularjs 进行登录

angularjs - 使用 multipartFile 上传图像的注册表单