如何在angularjshttp中添加访问令牌

how to add access token in angularjs http

本文关键字:添加 访问令牌 angularjshttp      更新时间:2023-09-26

我是一个新开发网站的人,使用angularJS作为我的客户端,我正在尝试通过API调用使用$http.get方法访问我的JSON。

我的问题是我的API调用需要一个访问令牌。每当我刷新页面时,总是会出现这个错误。

XMLHttpRequest无法加载http://unexus-api-dev-3urcgetdum.elasticbeanstalk.com/drugstores.请求的资源上不存在"Access Control Allow Origin"标头。原点'http://localhost:8888因此不允许访问。

我目前正在使用此代码来获取我的数据。

myApp.controller('loginCtrl', function($scope, $http) {
  $http.get("http://unexus-api-dev-3urcgetdum.elasticbeanstalk.com/drugstores")
    .then(function(response) {
      $scope.names = response.data.records;
    });
});

如何在$http.get方法上插入访问令牌。

这取决于您的API如何获取此访问令牌。最流行的选择是只需将特殊标题添加到您的请求

var req = {
   method: 'POST',
   url: 'http://example.com',
   headers: {
      'Authorization': 'access token'
   },
}
$http(req).then(function(){...}, function(){...});

你也可以在全球范围内添加

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

或使用角度拦截器http://www.diwebsity.com/2015/12/17/interceptor-in-angular/

您遇到了此处描述的SOP问题https://en.wikipedia.org/wiki/Same-origin_policy

你应该看看这里:

  1. 规避同源政策的方法
  2. 同源政策
  3. XMLHttpRequest同源策略