具有基本身份验证的HTTP请求返回401 - Angular 4上的标头问题

时间:2017-10-27 15:17:47

标签: angular api http http-headers

这是一篇经过编辑的帖子。我正在尝试使用API​​的简单http请求,其中包含基本身份验证(如user和pass)和params对象(绑定到表单);我已经阅读了文档,检查了几个帖子,但似乎没有任何工作;我总是得到401作为回应...

有些人可以帮我一下吗? (我是新来的)

这就是我所拥有的:

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;
         }
      }

2 个答案:

答案 0 :(得分:1)

我不知道我是否应该如何将您的数据发送到服务端点...但如果您通过标头发送邮件,那么您希望以正确的方式执行此操作,您应该使用angulars新功能,拦截器。通过这种方式,您可以为主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);
      }
    }

答案 1 :(得分:1)

由于post,我找到了解决方案。这是主要区别:

后:

function xhrAsync(url) {
    return new Promise((resolve, reject) => {
        GM_xmlhttpRequest({
            method: "GET",
            url: url,
            onload: resolve
        });
    });
}
function delayAsync(time) {
    return new Promise(resolve => {
        setTimeout(resolve, time);
    });
}
function getAPI(token) {
    console.log("Request API");
    return xhrAsync("URL"+token).then(response => {
//  ^^^^^^                       ^^^^
        console.log(response.responseText);
        if (response.responseText == "NOT_ANSWER" || response.responseText.includes("ERRO")) {
            console.log(response.responseText + " - Calling Myself in 5 Seconds");
            return delayAsync(5000).then(() => {
//          ^^^^^^                  ^^^^
                return getAPI(token);
//              ^^^^^^
            });
        } else {
            console.log('Call API - Giving Result');
            return response.responseText.split("_")[1];
        }
    });
}

现在:

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