后端基于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 }})
                }
            }
        }
    ]);

图片描述

图片描述

我是这样做的,但是仍然显示验证不通过。

阅读 7.5k
4 个回答

谢邀,手机上不方便给发送具体文章链接。主要给你思路哈。
应该登录后,每个请求都需要带token上去。一般会通过添加自定义请求头,然后AngularJS 1.x 有提供拦截器来实现这个功能哈。另外建议你也查找一下,MDN CORS的相关资料及$resource相关文档。
国外有很多AngularJS 1.x与JWT的应用示例,建议你Google搜索一下。

clipboard.png

在你的拦截器里面加上这个,jwt默认是放在headers的Authorization里面

clipboard.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进