Call API with Angular credentials

0

I have an application in Angular, which I want to make a call to a secure (endpoint) API with credentials (user & password).

I can do it with Ajax, but not with Angular.

AJAX / JQUERY Code:

jQuery.ajax('https://www.ENDPOINT.com/api/FLUJO/v1/POSTS', {
  type: 'GET',
  format: 'json',
  dataType: 'json',
  crossDomain: true,
  beforeSend: function(xhr) {
      xhr.setRequestHeader('Authorization', 'Basic ' + window.btoa(unescape(encodeURIComponent('USUARIO_ENDPOINT' + ':' + 'PASSWORD_ENDPOINT'))));
      xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
  },
  success: function(json_data) {
      jQuery('.result').html(JSON.stringify(json_data));
  },
  // In case of error, show an alert
  error: function() {
      alert('Failed!');
  }

})
.fail(function(jqXHR, textStatus, errorThrown) {
  let errorMessage = 'Request Failed (server response logged to console): ' + textStatus + ', ' + errorThrown + '. Server response: ' +
      jqXHR.responseText;
  jQuery('.noResult').html(errorMessage);
})
.done(function(json_data) {
  jQuery('.result').html(JSON.stringify(json_data));
});

The configuration of my project is as follows:

    _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _' | | | | |/ _' | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 7.0.7
Node: 10.13.0
OS: win32 x64
Angular: 7.0.4
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.10.7
@angular-devkit/build-angular     0.10.7
@angular-devkit/build-optimizer   0.10.7
@angular-devkit/build-webpack     0.10.7
@angular-devkit/core              7.0.7
@angular-devkit/schematics        7.0.7
@angular/cli                      7.0.7
@ngtools/webpack                  7.0.7
@schematics/angular               7.0.7
@schematics/update                0.10.7
rxjs                              6.3.3
typescript                        3.1.6
webpack                           4.19.1

And my service is like this:

//myservice.service.ts
    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders } from '@angular/common/http';

    @Injectable()
    export class MyserviceService {
      data: any = {};

      constructor(private http: HttpClient) {}

      createAuthorizationHeader(headers: Headers) {
        headers.append(
          'Authorization',
          'Basic ' + btoa('USSER_ENDPOINT:PASSWORD_ENDPOINT')
        );
      }

      callme()  {
        let headers = new HttpHeaders();
        this.createAuthorizationHeader(headers);
        return this.http.get('https://www.ENDPOINT.com/api/FLUJO/v1/POSTS', {
          headers: headers
        });
      }
    }

And this gives me the following compilation error:

ERROR in src/app/myservice.service.ts(21,36): error TS2345: Argument of type 'HttpHeaders' is not assignable to parameter of type 'Headers'.
  Property 'forEach' is missing in type 'HttpHeaders'.

Looking for the network I have not found anything, everyone uses FIREBASE, AUTH0, and in this case it can not be used, since it is a service provider.

What is closer is this, but I can not reproduce it:

link

It's a response from link

Any help and / or suggestion?

Thank you very much for your patience and help.

    
asked by Luiggi 04.12.2018 в 09:47
source

3 answers

2

I have works on a project with "@ angular / core": "^ 4.3.3" the following code in a service.ts:

@Injectable()
export class Api {

    // Declarations
    options: any;
    headers: any;

   constructor(private http: Http) {

        // Build Request Headers
        this.headers = new Headers(
            {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'User-Agent':'Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3'
            }
        );

        // Build Request Options
        this.options = new RequestOptions({
          method: RequestMethod.Get,
          headers: this.headers
        });
    }

    // PRODUCT  
    public getProduct(slug?: any) {
        return this.http.get('/GetProducts/' + slug + '.json').toPromise().then((res: Response) => { return res.json(); });
    }

}

You can try changing the way you set the headers. Maybe it works ...

:)

    
answered by 04.12.2018 в 13:33
1

I think the problem is in the way you are adding the headers. Try adding them with HttpInterceptor I leave you here a post where they explain it pretty well

link

    
answered by 04.12.2018 в 15:13
1

I see that the problem is with the API, which does not have a security certificate but it was found in https: // as if it had it.

So what happened to me to make the request for Back with NodeJS, with a flag to omit this certificate (before the request request).

I attached the flag if you are interested:

process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;

Thank you very much to both

    
answered by 05.12.2018 в 10:32