如何使用angular Http对mantisBT的REST API进行HTTP请求? [英] How to make HTTP REQUEST to mantisBT's REST API using angular Http?

查看:193
本文介绍了如何使用angular Http对mantisBT的REST API进行HTTP请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:

我在测试服务器上安装了mantisBT 2.5.0,并启用了REST API(目前处于测试阶段).之后,我生成了一个API密钥,并尝试使用/api/rest/swagger上的swagger页面发出测试HTTP请求.这很好. (我只能将.htaccess重命名为_htaccess后才能访问此页面)

I installed mantisBT 2.5.0 on a test server, enabled the REST API (which is currently in beta phase). After that I generated an API Key and I have tried to make a test HTTP request using the swagger page on /api/rest/swagger. This works fine. (I could only access this page after renaming the .htaccess to _htaccess)

我想做什么:

我想在我的应用程序中实现一项功能,从而无需直接访问mantisBT即可发送简单"的错误报告.为了测试API,我实现了此功能,该功能仅调用获取问题"请求.如果可行,我可以实现一种创建问题的方法.

I want to implement a feature in my app to enable sending "easy" bug reports without visiting mantisBT directly. To test the API I implemented this function, which just calls a "get issue" request. If this works, I can implement a method to create an issue.

问题:

我无法将带有API令牌的属性授权"添加到请求的HTTP标头中.结果是,每次我发出请求时,都会收到HTTP错误401.这似乎是授权问题.

I can't add the the attribute 'Authorization' with my API token to the HTTP headers of my request. The result is that every time I make the request I get a HTTP Error 401. It seems to be an authorization issue.

测试功能:

/**
* 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)复制的请求标头:

Request Header copied from the console (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

我认为错误是请求标头设置不正确.例如,它们不应具有访问控制请求头"的名称,而应仅具有授权"的名称.如何正确设置标题?

I think the error is that the request header are not set properly. They shouldn't have the name 'access-control-request-headers' but rather 'Authorization' only, for example. How can I set the headers properly?

编辑:如果我将应用托管在与mantisBT相同的域中,则一切正常.我不明白为什么.我将header( 'Access-Control-Allow-Origin: *' );添加到/api/rest/index.php

If I host my app on the same domain like mantisBT it all works fine. I don't understand why. I added header( 'Access-Control-Allow-Origin: *' ); to /api/rest/index.php

编辑:这似乎是服务器端的错误.现在我收到此错误:

It seems to be an error on server-side. Now I get this error:

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

肯定与认证标头发送不正确有关.

It definitively has something to do with the fact, that the authentification header is not sent properly.

推荐答案

我实现了一个对我有用的修复程序: (我正在使用POST发布功能,但没有使用get issue功能):

I implemented a fix which does work for me: (I got working the POST issue function, but not the get issue function):

<?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/json\r\n" .
                        "Authorization: " . $headers["Authorization"] . "\r\n",
                    "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/json\r\n" .
                    "Authorization: " . $headers["Authorization"] . "\r\n"
            ]
        ];
        $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

save this script to the mantis folder and use the url to this file as request target. I named it rest-fix.php

这篇关于如何使用angular Http对mantisBT的REST API进行HTTP请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆