2016-09-29 24 views
0

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

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

}); 

所以,我想知道的是,它是寫在$resourceheaders具有角JS的正確方法。 當我執行此代碼時,它顯示錯誤Error: No Token Supplied。並在console.log中也顯示一個錯誤POST http://localhost:3000/api/addblog 500 (Internal Server Error)

請幫忙。

+0

你得到的'req.headers.authorization'值發送您的要求? – abdulbarik

+0

沒有..它的'undefined' –

+0

在角度方面你可以在發送過程中獲得'$ rootScope.token'這個值嗎? – abdulbarik

回答

1

響應於OPTIONS請求,您的頭部必須包含在Access-Control-Allow-Headers標頭中。

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?

+0

仍然無法正常工作。 –

+0

你試過@nitish答案http://stackoverflow.com/questions/18924217/how-to-set-custom-headers-with-a-resource-action – abdulbarik

+0

是的.... @ nitish的答案正在工作...現在'console.log(req.headers.authorization);'正在打印'token' –

0

有許多方法可以在請求中設置授權令牌,它將基於用例。 這裏是我寫的answer,可能對你有幫助。