0

I m trying to rewrite an Ajax call in Angular. But getting always 401 Unauthorized. When i run the Ajax call, it works perfectly. Any idea how can i transfrom it to a Angular http request ? Thanks...

send(project) {
        let self = this;
        self.tasksURI = 'http://xxxx:xxxx/xx/xx/' + project + '/_apis/build/builds'
        self.PAT = 'xxxxxxxxxxxxxxxxxxxxx'
        self.ajax = function (uri, method, data) {
            var request = {
                url: uri,
                type: method,
                contentType: "application/json",
                accepts: "application/json",
                cache: false,
                dataType: 'json',
                data: JSON.stringify(data),
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("Authorization", "Basic " + btoa("" + ":" + "xxxxxxxxxx"));
                },
                error: function (jqXHR) {
                    console.log("ajax error " + jqXHR);
                }
            };
            return $.ajax(request);
        }

        self.ajax(self.tasksURI, 'GET').done((data) => {
            console.log(data)

        });
tlq
  • 887
  • 4
  • 10
  • 21

2 Answers2

0

In angular you try this:

In Angular

post(
    this.serverUrl, dataObjToPost,
    {
      headers: new HttpHeaders({
           'Content-Type':  'application/json',
         })
    }
)

back-end (I use php)

header("Access-Control-Allow-Origin: http://localhost:4200");
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header("Access-Control-Allow-Headers: Content-Type, Authorization");

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
print_r($request);

See No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

Harrison O
  • 1,119
  • 15
  • 20
  • xhr.setRequestHeader("Authorization", "Basic " + btoa("" + ":" + "xxxxxxxxxx")); exactly this part causing me problem. i dint know how to handle this part int the request – tlq Mar 07 '20 at 17:39
0

As you already mentioned you're getting "Unauthorised" judging from your situation this could mean 2 of things:

  1. You are not providing any Authorization header
  2. Your Authorization header is invalid

Since you're rewriting this I think it's most likely that you forgot to apply the Authorization header to your httpOptions

From the Angular docs:

httpOptions.headers =
  httpOptions.headers.set('Authorization', 'my-new-auth-token');
Ramon Gebben
  • 534
  • 4
  • 17
  • xhr.setRequestHeader("Authorization", "Basic " + btoa("" + ":" + "xxxxxxxxxx")); exactly this part causing me problem. i dint know how to handle this part int the request – tlq Mar 06 '20 at 16:58