2017-10-27 15 views
0

これは編集済みの投稿です。私は基本的な認証(ユーザーとパスのような)とparamsオブジェクト(フォームにバインド)を持つAPIからこの単純なhttpリクエストを試しています。私はドキュメントを読んで、いくつかの投稿をチェックアウトしましたが、何も動作していないようです。私は常に401として応答を得ます...基本認証でHTTPリクエストが返される401 - 角4のヘッダーで問題が発生する

いくつか私に助けを与えることができますか?

これは私が持っているものである(私はこの時に新たなんだ):

import { Component, OnInit } from '@angular/core'; 
import {HttpClient} from '@angular/common/http'; 
import {Http, Headers} from '@angular/http'; 
import {response} from '../../models/response'; 
import {HttpErrorResponse} from '@angular/common/http'; 
import {HttpHeaders} from '@angular/common/http'; 

@Component({ 
    selector: 'app-testing', 
    templateUrl: './testing.component.html', 
    styleUrls: ['./testing.component.css'] 
}) 

export class TestingComponent implements OnInit { 

    //OPTIONS 
    selectedColor:string; 
    selectedFont:string; 
    selectedSize:string; 

    //INTERFACE 
    results: response; 


    params = { 
    "handwriting_id": "8X3WQ4D800B0", 
    "text": "", 
    "handwriting_size": "", 
    "handwriting_color": "", 
    } 

    constructor(private http: HttpClient) { } 

    ngOnInit() { 
    } 

    onSubmit(f){ 

     console.log(this.params); 

     this.http.get<Response>('https://api.handwriting.io/render/png?' + this.params,{ 
     headers: new HttpHeaders().set('7Q0ZBC889M7WRGRM','N6BQK4Z8PZ1HYYT4'), 
     }).subscribe(data => { 
     this.results = data['results']; 
     console.log(this.results); 

     },(err: HttpErrorResponse) => { 
      if (err.error instanceof Error) { 
      console.log('An error occurred:', err.error.message); 
      } else { 
      console.log(`Backend returned code ${err.status}, body was: ${err.error}`); 
      } 
     }); 
    } 

    //OPTIONS 

    changeFont(){ 
     document.getElementById("output-text").style.fontFamily = this.selectedFont; 
     } 
    changeColor(){ 
    document.getElementById("output-text").style.color = this.selectedColor; 
     } 
    changeSize(){ 
    document.getElementById("output-text").style.fontSize = this.selectedSize; 
     } 
     } 
+0

ここでの主な違いはありますか?それは要求と一緒に送信されるように見えません。おそらくそれをヘッダオブジェクトに追加しますか? – Ric

+0

環境にいくつかの値を追加しても、魔法のようにHTTPリクエストを使って資格情報をヘッダーとして送信することはありません。 Httpのドキュメントを読んで、適切なヘッダーを送る必要があります。また、あなたは環境内で価値観を見つけることができます。 Httpは間もなく廃止される予定です。 HttpClientの使い方を学ぶ方がいいでしょう。 –

+0

@FRECIAは完了しましたが、プロバイダとしてHttpHandlerを受け入れることはまだありません... – Mellville

答えて

0

私は解決策にこのpostに感謝を発見しました。

後:今

headers: new HttpHeaders().set('7Q0ZBC889M7WRGRM','N6BQK4Z8PZ1HYYT4'), 
     }).subscribe(data => {//etc 

:あなたは環境データを使用している

headers: new HttpHeaders().set('Authorization', 'Basic ' + 
     btoa('STRSKVENJVBD0JDS:4ZN6VD256FEBHSM1')) 
     }).subscribe(data =>//etc 
1

私はあなたがサービスのエンドポイントにデータを取得することになっている方法を取得する場合は知らない...しかし、もしヘッダーを介して郵便配達員と一緒に送った後、適切なやり方をしたいと思っています。こうすることで、メインのapp.moduleに簡単なインターセプタを提供し、サービスで新しいhttpClientを使用することができます。この方法では、サービスによって行われたすべてのリクエストにヘッダが自動的に追加されます。ここで

は、あなたのケースのためにリファクタリングする必要があり、簡単なチュートリアルです:

1)インターセプタを作成:

import {Injectable} from '@angular/core'; 
import {HttpRequest,HttpHandler,HttpEvent,HttpInterceptor} from '@angular/common/http'; 
import {Observable} from 'rxjs/Observable'; 
@Injectable() 
export class Interceptor implements HttpInterceptor { 
    constructor() {} 
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 

     request = request.clone({ 
      setHeaders: { 
       Authorization: `Bearer ${YOUR_TOKEN}` <-- the API should expect a token here 
      } 
     }); 

    return next.handle(request); 
    } 
} 

2)あなたのメインモジュールでインターセプタを提供します(通常はapp.module.ts ):

import {HTTP_INTERCEPTORS} from '@angular/common/http'; 
import {Interceptor} from './path/to/interceptor'; 
@NgModule({ 
    bootstrap: [AppComponent], 
    imports: [...], 
    providers: [{provide: HTTP_INTERCEPTORS,useClass: Interceptor,multi: true}] 
}) 

export class AppModule {} 

3)インターセプタを適用します新しいHttpClientを(角4.3)を使用して、サービスに:

import { HttpClient } from '@angular/common/http'; <-- IMPORTANT new httpClient 

export class DataService { 

    constructor(public http:HttpClient) { 

    } 

    getPNG(){ 
     return this.http.get('https://api.handwriting.io/render/png') 
      .map(res => res); 
    } 

     addHand(user){ 
     return this.http.post('https://api.handwriting.io/render/png', user) 
      .map(res => res); 
     } 
    } 
+0

@ FRECIAの無償回答に感謝しますが、cli経由でどのようにインターセプタを生成できますか? – Mellville

+0

あなたの指示に従ってきましたが、まだいくつかの問題があります:interceptor.tsファイルを '../ services/data.service 'から' import {AuthService}'してください;これに下線を引いてください:{'TokenInterceptor} from './interceptor/interceptor';' – Mellville

+0

私はまだ401を取得します...つまり、資格証明が送信されていません...彼らの場所はありませんか? '要求= request.clone({ はsetHeaders:{ キー: "7Q0ZBC889M7WRGRM"、 秘密: "N6BQK4Z8PZ1HYYT4" } は});' – Mellville

関連する問題