无法设置content-type = application / json angular4 post请求

时间:2017-09-29 10:08:43

标签: angular post http-headers content-type

我正在尝试使用angularjs4发送帖子请求。代码在到达login()函数时工作正常。注意this.http.post函数,如果我删除最后一个参数,即make请求看起来像return this.http.post('http://localhost:8080/auth', JSON.stringify({ username: username, password: password }),那么web api上的请求标题就变为:

POST /auth HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 39
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/plain, */\*
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
content-type: text/plain
Referer: http://localhost:4200/login
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6

注意默认情况下由angularjs设置的content-type:text/plain。所以我尝试添加{ headers: head}来将content-type更改为application/json,然后将Invalid CORS request显示为响应并将Request Header转换为:

Accept:*/\*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
.
.

注意Access-Control-Request-Headers:content-type行,当然这是错误的。 以下是启动请求的授权文件:

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

@Injectable()
export class AuthenticationService {
 public token: string;

constructor(private http: Http) {

}

login(username: string, password: string): Observable<boolean> {
    let head = new Headers({ 'Content-Type': 'application/json' });
    return this.http.post('http://localhost:8080/auth', JSON.stringify({ username: username, password: password }),{ headers: head})
        .map((response: Response) => {
            // login successful if there's a jwt token in the response
            let token = response.json() && response.json().token;
            console.log(response);

        });
}


}

请通过AngularJS 4建议在发布请求中将内容类型更改为application/json的正确方法

3 个答案:

答案 0 :(得分:4)

使用以下代码

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

@Injectable()
export class AuthenticationService {
 public token: string;

constructor(private http: Http) {

}

login(username: string, password: string): Observable<boolean> {
   // let head = new Headers({ 'Content-Type': 'application/json' });
  const headers = new Headers();
  headers.append('Content-Type', 'application/json');
  let options = new RequestOptions({ headers: headers });
    return this.http.post('http://localhost:8080/auth', JSON.stringify({ username: username, password: password }),options)
        .map((response: Response) => {
            // login successful if there's a jwt token in the response
            let token = response.json() && response.json().token;
            console.log(response);

        });
}


}

答案 1 :(得分:3)

您应该能够以这种方式使用标题:

let headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });

return this.http.post('http://localhost:8080/auth', JSON.stringify({ username: username, password: password }), options)
    .map((response: Response) => {
        // login successful if there's a jwt token in the response
        let token = response.json() && response.json().token;
        console.log(response);    
    });

或者,我相信如果您使用HttpClient中较新的@angular/common/http,则application / json是默认的内容类型。

E.g。 - 首先导入HttpClientModule:

// app.module.ts:

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

// Import HttpClientModule from @angular/common/http
import {HttpClientModule} from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // Include it under 'imports' in your application module
    // after BrowserModule.
    HttpClientModule,
  ],
})
export class MyAppModule {}

然后,在您的AuthenticationService中:

constructor(private http: HttpClient) {}

login(username: string, password: string): Observable<boolean> {
    return this.http.post('http://localhost:8080/auth', JSON.stringify({ username: username, password: password }))
        .map((response: Response) => {
            // login successful if there's a jwt token in the response
            let token = response.json() && response.json().token;
            console.log(response);    
        }); 
}

Angular Documentation中提供了更多信息。

答案 2 :(得分:1)

试试这个:

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

    @Injectable()
    export class AuthenticationService {
     public token: string;

    constructor(private http: Http) {

    }

    login(username: string, password: string): Observable<boolean> {
        let head = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: head });
        return this.http.post('http://localhost:8080/auth', JSON.stringify({ username: username, password: password }),options)
            .map((response: Response) => {
                // login successful if there's a jwt token in the response
                let token = response.json() && response.json().token;
                console.log(response);

            });
    }


    }