Angular 5:HTTP post`对预检的响应具有无效的HTTP状态代码400

时间:2018-04-03 18:46:47

标签: javascript angular typescript http-headers

我有以下服务;无论我配置多少,我都无法获得http请求。

Chrome控制台错误 Response for preflight has invalid HTTP status code 400. enter image description here

我的服务

import { Injectable } from '@angular/core';
import { Http, RequestOptions, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';



@Injectable()
export class SlackService {
    extractData(res: Response) {
        let body = res.json();
        return body || {};
    }
    handleError (error: Response | any) {
        console.error(error.message || error);
        return Promise.reject(error.message || error);
    }

    private url: string = 'https://hooks.slack.com/services/xxx/xxx/xxx';

    constructor(private http: Http) {}

    public slack(data: any): Observable<{}> {
        let body = JSON.stringify(data);
        let headers: Headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let options = new RequestOptions({ headers: headers });

        return this.http.post(this.url, body, options)
            .map(this.extractData)
            .catch(this.handleError);
    }

}

我记得在AngularJS中遇到这个问题,以下修复了它......角度2 +中的等价物是什么?

app.config(function ($httpProvider) {
  $httpProvider.defaults.headers.common = {};
  $httpProvider.defaults.headers.post = {};
  $httpProvider.defaults.headers.put = {};
  $httpProvider.defaults.headers.patch = {};
}); 

我见过这样的答案Angular 2 Token: Response for preflight has invalid HTTP status code 400,但没有帮助

这在PostMan中起作用

curl -X POST \
  https://hooks.slack.com/services/xx/xx/xx \
  -H 'content-type: application/x-www-form-urlencoded' \
  -d payload=%7B%0A%20%20%20%20%20%20%22channel%22%3A%20%22%23general%22%2C%0A%20%20%20%20%20%20%22username%22%3A%20%22webhookbot%22%2C%0A%20%20%20%20%20%20%22text%22%3A%20%22This%20is%20posted%20to%20%23general%20and%20comes%20from%20a%20bot%20named%20webhookbot.%22%2C%0A%20%20%20%20%20%20%22icon_emoji%22%3A%20%22%3Aghost%3A%22%0A%20%20%20%7D

3 个答案:

答案 0 :(得分:0)

看来您的有效负载必须是param而不是json 试试这个,如果你有jQuery

import { Injectable } from '@angular/core';
import { Http, RequestOptions, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
declare var $: any


@Injectable()
export class SlackService {
    extractData(res: Response) {
        let body = res.json();
        return body || {};
    }
    handleError (error: Response | any) {
        console.error(error.message || error);
        return Promise.reject(error.message || error);
    }

    private url: string = 'https://hooks.slack.com/services/xxx/xxx/xxx';

    constructor(private http: Http) {}

    public slack(data: any): Observable<{}> {
        let body = $.param(data);
        let headers: Headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');

        let options = new RequestOptions({ headers: headers });

        return this.http.post(this.url, body, options)
            .map(this.extractData)
            .catch(this.handleError);
    }

}

或者尝试新的HttpClient很快就会弃用旧的htpp库,请参阅here

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';



@Injectable()
export class SlackService {

    handleError (error: Response | any) {
        console.error(error.message || error);
        return Promise.reject(error.message || error);
    }

    private url: string = 'https://hooks.slack.com/services/xxx/xxx/xxx';

    constructor(private http: HttpClient) {}

    public slack(data: any): Observable<{}> {
        const requestOptions = {
            params: new HttpParams()
        };
        //Add all your payload here
        requestOptions.params.set('foo', 'bar');


        return this.http.post(this.url, requestOptions , {
            headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' })
        })
       .map((res) => res.json())
       .catch(this.handleError);
    }

}

答案 1 :(得分:0)

对我来说,看起来API缺少CORS配置( OPTIONS http方法)。

如果来源不同,现代网络浏览器会首先请求 OPTIONS (飞行前)。

基本上你需要做的就是在你的后端配置CORS - 前端与它无关。

有关CORS

的更多信息

答案 2 :(得分:-1)

尝试更改以下代码行:

headers.append('Content-Type', 'application/json');

headers.set('Content-Type', 'application/x-www-form-urlencoded');