1

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

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

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

URL + users?token= token

但这会返回:

格式为授权:Bearer [token]

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

4

3 回答 3

0

你可以像这样创建一个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');
})
于 2015-10-22T15:36:15.833 回答
0

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

格式为授权:Bearer [token]

你可以在 Postman 中试试这个

邮递员配置

于 2015-10-22T15:41:58.840 回答
0

您需要将标头添加到http

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

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

于 2015-10-22T15:29:49.697 回答