【问题标题】:How to properly call a protected API route with a token如何使用令牌正确调用受保护的 API 路由
【发布时间】:2016-01-21 22:49:21
【问题描述】:

我的 API 应用中有这条路线:

router.get('/users', auth, function(req, res) {
  User.find({}, function(err, users) {
    res.json(users);
  });
});

在邮递员中,我像这样进行 api 调用:

URL + users?token=token

但这会返回:

格式为授权:Bearer [token]

如何在邮递员中正确地使用令牌进行 api 调用?

【问题讨论】:

  • 试图在标题中发送这个?

标签: angularjs node.js postman express-jwt


【解决方案1】:

您得到的错误表明您需要为标题使用正确的格式:

格式为授权:Bearer [token]

你可以在 Postman 中试试这个

【讨论】:

    【解决方案2】:

    需要在http中添加header

    module.run(function($http) {
      $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
    });
    

    执行此操作后,您的请求将与此标头一起发送 看看https://docs.angularjs.org/api/ng/service/$http

    【讨论】:

    • 在邮递员中,您可以添加标题,因此添加标题,名称为“授权”,然后添加值“基本 YmVlcDpib29w”无列
    • 那么我在哪里添加令牌?我已经用我的登录调用生成了一个令牌,但是我应该将它粘贴到邮递员的哪里
    • 因此,当您单击关键字段中的标题按钮时,您在值字段中键入“授权”,然后键入“基本 yourToken”
    • 这是 Bearer token 我需要输入
    【解决方案3】:

    你可以像这样创建一个http拦截器服务

    app.factory('authInterceptor', function($rootScope, $q, $cookieStore, $location) {
        return {
            // Add authorization token to headers
            request: function(config) {
                config.headers = config.headers || {};
                if ($cookieStore.get('token')) {
                    config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
                }
                return config;
            },
    
            // Intercept 401s and redirect you to login
            responseError: function(response) {
    
                if (response.status === 401) {
                    $location.path('/login');
                    // remove any stale tokens
                    $cookieStore.remove('token');
                    return $q.reject(response);
                } else {
                    return $q.reject(response);
                }
            }
        };
    })
    

    然后像这样将服务添加到拦截器中

    app.config(function($httpProvider) {
          $httpProvider.interceptors.push('authInterceptor');
    })
    

    【讨论】:

      猜你喜欢
      • 2019-11-22
      • 1970-01-01
      • 2020-08-18
      • 2021-05-03
      • 1970-01-01
      • 2020-08-21
      • 2018-05-13
      • 1970-01-01
      • 2021-04-06
      相关资源
      最近更新 更多