在HTTP请求中发送HTTP标头,例如邮递员

时间:2018-08-22 02:02:31

标签: angular http-headers http-post postman

Angular无法发送http发布请求,但出现此错误:

解析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格式错误。但是我不知道如何使标题与邮递员标题相同

1 个答案:

答案 0 :(得分:0)

按角度发送http标头的最佳方法是使用拦截器。

Header Interceptor File ..

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 }