【问题标题】:Send HTTP headers in HTTP request like postman像邮递员一样在 HTTP 请求中发送 HTTP 标头
【发布时间】:2018-08-22 02:02:31
【问题描述】:

Angular 发送 http post 请求失败,我收到了这个错误:

解析http://axis2.icd.teradyne.com:8080/test时的Http失败

service.ts

currentUse(SVF){
    //let options = {headers: new HttpHeaders({'Content-Type': 'application/json'})};
    const httpOptions = {
        headers: new HttpHeaders({
        'Content-Type':  'application/json'
        //'Access-Control-Allow-Origin': 
        })
    };
    httpOptions.headers.set('Access-Control-Allow-Origin','http://axis2.icd.teradyne.com:8080');

    return this.http.post<any>('http://axis2.icd.teradyne.com:8080/test', SVF, httpOptions)
    .pipe(catchError(this.handleError))
}

如果我使用邮递员发送请求,它可以工作。

这是邮递员的标题:

Access-Control-Allow-Origin →*
Content-Length →4
Content-Type →text/html; charset=utf-8
Date →Wed, 22 Aug 2018 01:09:10 GMT
Server →Werkzeug/0.14.1 Python/3.6.2

我想知道问题是否是因为 httpheader 的格式错误。但是不知道怎么才能让header和postman header一样

【问题讨论】:

    标签: angular http-headers http-post postman


    【解决方案1】:

    以 Angular 发送 http 标头的最佳方式是使用拦截器。

    头拦截器文件..

    import { Injectable } from '@angular/core';
    import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
    
    import { Observable } from 'rxjs';
    
    
    @Injectable({   providedIn: 'root' })
    export class HeaderInterceptor implements HttpInterceptor {
    
        intercept(req: HttpRequest<any>, next: HttpHandler):
            Observable<HttpEvent<any>> {
                req = req.clone({ headers: req.headers.set('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8') });
            return next.handle(req);
        }
    }
    

    在你的 appmodule 文件中 使用下面的行来导入拦截器。

    import { HttpClientModule, HttpClient, HTTP_INTERCEPTORS } from '@angular/common/http';
    

    将此添加到您的提供程序数组中

    { provide: HTTP_INTERCEPTORS, useClass: HeaderInterceptor, multi: true }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2014-09-25
      • 2023-04-01
      • 2018-03-17
      • 2017-02-07
      • 2016-11-10
      • 2011-09-20
      相关资源
      最近更新 更多