使用带有授权头的API

时间:2018-08-08 13:41:46

标签: javascript api

使用API​​时遇到很大的问题。我正在尝试倾斜请求数据的基础。

测试API的网址是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。

2 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

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请求添加“授权”标头

答案 1 :(得分:0)

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

要解决此问题,可以在后端允许跨域,这将解决此问题。

相关问题