【问题标题】:Consuming API with Authorization Header使用授权标头使用 API
【发布时间】:2018-08-08 22:18:43
【问题描述】:

我在使用 API 时遇到了很大的问题。我正在尝试学习请求数据的基础知识。

测试 API 的 url 是 aq-test.000webhostapp.com/v1/,它返回一个简单的“hello world”,没有问题。

向 aq-test.000webhostapp.com/v1/users 发出 GET 请求会返回所有创建的用户(只有一个)。这个 API PHP 服务器有一个验证函数,当我向它发出请求时,它会检查标头是否具有授权令牌:

$headers = apache_request_headers();
$response = array();
$app = \Slim\Slim::getInstance();

// Verifying Authorization Header
if (isset($headers['Authorization'])) {

    // get the api key
    $token = $headers['Authorization'];

    // validating api key
    if (!($token == API_KEY)) { //Do Stuff}

我的问题是,我正在发送带有 Autorization 令牌的标头,但它根本不起作用。这是我的代码:

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://aq-test.000webhostapp.com/v1/users",
  "method": "GET",
  "headers": {
    'Content-Type' : 'application/x-www-form-urlencoded',
    'Authorization': '3d524a53c110e4c22463b10ed32cef9d'
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

无论我做什么,我总是收到不好的请求。我什至使用 AngularJS 的 $http.get 发送标头来做到这一点,但它没有用。

这很奇怪,但如果我使用 PostMan 发出请求,(PostMan 文件 https://www.dropbox.com/s/3ms71lbnu1jb4wj/api_test.postman_collection?dl=0)它可以完美运行。事实上,我的代码是基于 PostMan 的请求!我在这里做错了什么?

希望大家能不吝赐教,因为我是无能的atm。

【问题讨论】:

标签: javascript api


【解决方案1】:

你可以试试这个:

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://aq-test.000webhostapp.com/v1/users",
  "method": "GET",
  "headers": {
    'Content-Type' : 'application/x-www-form-urlencoded',
  },
  beforeSend: function (xhr) {
     xhr.setRequestHeader ("Authorization", "3d524a53c110e4c22463b10ed32cef9d")
  },
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

这将为 json 请求添加一个“授权”标头

【讨论】:

【解决方案2】:

您收到与 OPTIONS 请求相关的错误。这是same-origin policy 的问题。 浏览器是 preflighting the request 来查找 CORS 标头。如果请求是可接受的,它将发送真正的请求。

要修复它允许在后端跨域,这将解决这个问题。

【讨论】:

  • 后端已经开启跨域:header("Access-Control-Allow-Origin: null"); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS'); header("Access-Control-Allow-Headers: X-Requested-With"); header('Content-Type: text/html; charset=utf-8'); header('P3P: CP="IDC DSP COR CURa ADMa OUR IND PHY ONL COM STA"');
  • 添加“*”通配符而不是null
  • header("Access-Control-Allow-Origin: *");
  • 更改为 header("Access-Control-Allow-Origin: *");还是一样!
猜你喜欢
  • 2020-06-03
  • 2017-12-08
  • 2018-08-13
  • 2016-07-02
  • 2016-07-15
  • 2021-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多