首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有基本auth的HTTP请求返回401 -在角4上发出标头

带有基本auth的HTTP请求返回401 -在角4上发出标头
EN

Stack Overflow用户
提问于 2017-10-27 15:17:46
回答 2查看 2.1K关注 0票数 0

这是一篇经过编辑的文章。我正在尝试这个来自API的简单http请求(比如用户和pass)和一个params对象(绑定到一个表单);我已经阅读了文档,检查了几个帖子,但是似乎没有什么工作;我总是得到401作为响应.

有人能帮我吗?(我是新来的)

这就是我得到的:

代码语言:javascript
复制
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;
         }
      }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-10-29 18:57:26

多亏了这个post,我找到了解决方案。这里的主要区别是:

之后:

代码语言:javascript
复制
headers: new HttpHeaders().set('7Q0ZBC889M7WRGRM','N6BQK4Z8PZ1HYYT4'),
      }).subscribe(data => {//etc

现在:

代码语言:javascript
复制
headers: new HttpHeaders().set('Authorization', 'Basic ' +
        btoa('STRSKVENJVBD0JDS:4ZN6VD256FEBHSM1'))
      }).subscribe(data =>//etc
票数 1
EN

Stack Overflow用户

发布于 2017-10-27 16:20:09

我不知道你应该如何把你的数据送到服务端点.但是,如果您通过邮件头发送它,那么您想要以正确的方式发送它,您应该使用angulars新特性,即拦截器。这样,您可以为您的主app.module提供一个简单的拦截器,并在您的服务中使用新的httpClient .这样,标头将自动添加到服务完成的每个请求中。

下面是一个简单的演练,您应该为您的情况重构:

1)创建拦截器:

代码语言:javascript
复制
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)中提供拦截器:

代码语言:javascript
复制
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):将拦截器应用于您的服务

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46978387

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档