angular.js - 后端基于JWT驗證,Angular post 請求如何攜帶token?
問題描述
當用戶成功登錄后獲取后端返回的token
userService.loginUser(user).then(function(response) { $cookies.put('token', response.token) ...
然后,更新個人信息時,如何攜帶這個token呢?
token = $cookies.get('token')console.log(token)studentService.edit(token).save({studentId: $scope.student.id}, student, function(response) {console.log(response)
studentService
angular.module(’app’) .factory(’studentService’, [’$resource’,function($resource) { return {detail: function() { return $resource(’/api/student/:studentId/ ’, {studentId: ’@studentId’ })},edit: function(token) { return $resource(’/api/student/:studentId/edit/ ’, {studentId: ’@studentId’ },{headers: { ’auth-token’: token }})} }} ]);
我是這樣做的,但是仍然顯示驗證不通過。
問題解答
回答1:{withCredentials:true} 科普連接
回答2:謝邀,手機上不方便給發送具體文章鏈接。主要給你思路哈。應該登錄后,每個請求都需要帶token上去。一般會通過添加自定義請求頭,然后AngularJS 1.x 有提供攔截器來實現這個功能哈。另外建議你也查找一下,MDN CORS的相關資料及$resource相關文檔。國外有很多AngularJS 1.x與JWT的應用示例,建議你Google搜索一下。
回答3:用angularjs-jwt,在每個請求頭上加上token,參考:github地址https://github.com/auth0/angu...
