如何使用令牌正确调用受保护的 API 路由

How to properly call a protected API route with a token

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

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

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

URL + users?token=token

但是这个returns:

Format is Authorization: Bearer [token]

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

您需要将 header 添加到 http

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

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

你可以像这样创建一个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');
})

您收到的错误表明您需要为 header 使用正确的格式:

Format is Authorization: Bearer [token]

你可以在 Postman 中试试这个