简体   繁体   English

Angular2 ES5 - 覆盖HTTP POST标头中的Content-Type

[英]Angular2 ES5 - overriding Content-Type in HTTP POST header

Trying to override content type for the header, but it's still coming at text/plain. 试图覆盖标题的内容类型,但它仍然是text / plain。 There's a way to doit with Ben Nadel's GateWayAPI, but hoping there's a solution that doesn't involve custom wrapping. 有一种方法可以用Ben Nadel的GateWayAPI,但希望有一个不涉及自定义包装的解决方案。

    var url = this.url;
    var body = JSON.stringify({email_login: "login", password_login: "password"});
    var headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });


    return this.http.post(url, body, {headers:headers})
        .map(function (response) {
            return response.json();
        })
        .catch(this.handleError);

How about using the append function instead: 如何使用append函数代替:

let headers = new Headers();
headers.append("Content-Type", "application/x-www-form-urlencoded");

Request post of Http have the following signature: Http请求post有以下签名:

post(url: string, body: any, options?: RequestOptionsArgs)

Third argument is parameter with type RequestOptionsArgs , which means you have to pass RequestOptions to it, not Headers . 第三个参数是RequestOptionsArgs类型的参数,这意味着您必须将RequestOptions传递给它,而不是Headers You also should use arrow operator ( => ) instead of function . 您还应该使用箭头操作符( => )而不是function What you are looking for is something like this: 你在寻找的是这样的:

result: any;

httpPostTest() {

var url = this.url;
var body = JSON.stringify({email_login: "login", password_login: "password"});

let headers: Headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded' });
let options: RequestOptions = new RequestOptions({ headers: headers });

this.http.post(url, body, options)
    .map(response => {
        response = response.json();
    })
    .catch(this.handleError);
}

After this, you need to use subscribe to get response , so let's say that this function is called httpPostTest (I'll add it above) and we want to store response in variable called result : 在此之后,你需要使用subscribe来获得response ,所以让我们说这个函数叫做httpPostTest (我将它添加到上面),我们想要将响应存储在名为result变量中:

this.httpPostTest().subscribe(
            response => { this.result = response; },
            error => { console.log('ERROR'); },
            () => { console.log('FINISHED')}
);

You should create an instance of the RequestOptions class and use strings instead of json objects as you are using form-urlencoded: 您应该创建RequestOptions类的实例,并在使用form-urlencoded时使用字符串而不是json对象:

 var body = "email_login=login&password_login=password";
 var headers = new Headers();
 headers.append('Content-Type', 'application/x-www-form-urlencoded');
 let options = new RequestOptions({ headers: headers });
 this.http.post(url, body, options);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM