簡體   English   中英

無法設置content-type = application / json angular4發布請求

[英]Unable to set content-type = application/json angular4 post request

我正在嘗試使用angularjs4發送發布請求。 到達login()函數時,代碼可以正常工作。 請注意this.http.post函數,如果我刪除了最后一個參數,即使請求看起來像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

注意content-type:text/plain ,默認情況下由angularjs設置。 所以我嘗試添加{ 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在后期請求中的Request Header中將內容類型更改為application/json的正確方法

使用以下代碼

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);

        });
}


}

您應該能夠以這種方式使用標頭:

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);    
    });

另外,我相信如果您使用@angular/common/http較新的HttpClient ,則application / json是默認的內容類型。

例如-首先導入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文檔中提供了更多信息。

嘗試這個:

    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);

            });
    }


    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM