如何使用角度 Http 向 mantisBT 的 REST API 发出 HTTP 请求?



背景:

我在测试服务器上安装了Mantisbt 2.5.0,启用了REST API(当前处于Beta阶段(。之后,我生成了一个API键,并且尝试使用/API/REST/SWAGGER的Swagger页面进行测试HTTP请求。这很好。(我只能在将.htaccess重命名为_htaccess之后访问此页面(

我想做什么:

我想在我的应用中实现一个功能,以启用无需直接访问Mantisbt的"简单"错误报告。为了测试API,我实现了此功能,该功能刚刚称为" get Issup"请求。如果有效,我可以实现一种创建问题的方法。

问题

我无法将我的API令牌"授权"添加到我请求的HTTP标题中。结果是,每次我提出请求时,我都会收到HTTP错误401。这似乎是一个授权问题。

测试功能

/**
* function to test the API
* @returns {Observable<Response>}
*/
getIssue(): Observable<Response> {
  const api_token = 'XXXXXX';
  const params: URLSearchParams = new URLSearchParams();
  params.set('id', '1');
  const url = 'https://anydomain/mantisbt/api/rest/issues';
  const requestOptions = new RequestOptions({
     method: RequestMethod.Get,
     url: url,
     params: params,
     headers: new Headers({
       'Content-Type': 'application/json',
       'Authorization': api_token
     })
   });
   const req = new Request(requestOptions);
   return this.http.request(req);
}
...
this.getIssue().subscribe((result)=>{console.log(result)});

请求从控制台(Chrome(复制的请求标头:

:authority:XXXXXXXX
:method:OPTIONS
:path:/mantisbt/api/rest/issues?id=1
:scheme:https
accept:*/*
accept-encoding:gzip, deflate, sdch, br
accept-language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
access-control-request-headers:authorization,content-type
access-control-request-method:GET
dnt:1
origin:http://localhost
referer:http://localhost/login
user-agent:XXXXXXXX

我认为错误是请求标头未正确设置。他们不应该拥有"访问权利 - 重点标题"的名称,而是仅仅是"授权"。我如何正确设置标题?

编辑:如果我在像Mantisbt这样的同一域上托管了我的应用程序,则可以正常工作。我不明白为什么。我将header( 'Access-Control-Allow-Origin: *' );添加到/Api/Rest/index.php

编辑:这似乎是服务器端的错误。现在我得到了这个错误:

XMLHttpRequest cannot load https://XXXXXX/api/rest/issues?id=1.
Response for preflight has invalid HTTP status code 401

它绝对与以下事实有关,即确定的标题未正确发送。

首先创建标头和urlsearchparams,然后添加到选项中。

let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization': api_token);
let params = new URLSearchParams();
params.set('id', '1');
let options = new RequestOptions({ headers: headers, search: params });
return this.http
    .get(url, options);

我实施了一个对我有用的修复程序:(我从事邮政问题功能,但没有get问题函数(:

<?php
$api_url = "https://XXXXXXXXXX/api/rest/issues"; //insert api url here
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: authorization, content-type');
header('Access-Control-Allow-Methods: POST,GET,OPTIONS,DELETE');
if (!function_exists('getallheaders')) {
    function getallheaders()
    {
        $headers = [];
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }
        return $headers;
    }
}
$headers = getallheaders();
$method = $headers['Access-Control-Request-Method'];
$data = file_get_contents("php://input");
if (!empty($data)) {
    $method = 'POST';
} else if (!empty($_GET)) {
    $method = 'GET';
}
switch ($method) {
    case ('POST'):
        postRequest($headers, $api_url);
        break;
    case ('GET'):
        getRequest($headers, $api_url);
        break;
    case ('DELETE'):
        break;
}
function postRequest($headers, $api_url)
{
    // POST REQUEST
    $data = file_get_contents("php://input");
    if (!empty($data)) {
        $data = json_decode($data, true);
        if ($headers["Authorization"] != null) {
            $opts = [
                "http" => [
                    "method" => "POST",
                    "header" => "Accept: application/jsonrn" .
                        "Authorization: " . $headers["Authorization"] . "rn",
                    "content" => http_build_query($data)
                ]
            ];
            $context = stream_context_create($opts);
            // Open the file using the HTTP headers set above
            $file = file_get_contents($api_url, false, $context);
            echo $file;
        }
    }
}
function getRequest($headers, $api_url)
{
    // GET REQUEST
    print_r($_GET);
    if ($headers["Authorization"] != null) {
        $opts = [
            "http" => [
                "header" => "Accept: application/jsonrn" .
                    "Authorization: " . $headers["Authorization"] . "rn"
            ]
        ];
        $context = stream_context_create($opts);
        // Open the file using the HTTP headers set above
        $file = file_get_contents($api_url . "?" . http_build_query(array("id" => 10)), false, $context);
        echo $file;
    }
}
?>

将此脚本保存到MANTIS文件夹,并将其用作请求目标的URL。我将其命名为REST-fix.php

相关内容

  • 没有找到相关文章

最新更新