简体   繁体   中英

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

I am trying to send a post request using angularjs4. Code works fine while it reaches the login() function. Note the this.http.post function, if I remove the last param ie make request look like return this.http.post('http://localhost:8080/auth', JSON.stringify({ username: username, password: password }) , then the request header on web api becomes :

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

Note the content-type:text/plain which is set by angularjs by default. So I tried adding { headers: head} to change the content-type to application/json which in turns shows Invalid CORS request as response and turns the Request Header to :

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
.
.

Notice the Access-Control-Request-Headers:content-type line, which of course is wrong. Below is the Authorization file which initiates the request:

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

        });
}


}

Please suggest the proper way to change the content type to application/json in Request Header in post request via AngularJS 4

Use Below Code

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

        });
}


}

You should be able to use a header in this way:

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

Alternatively, I believe that if you use the newer HttpClient from @angular/common/http , application/json is the default content-type.

Eg - Firstly import the 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 {}

Then, in your 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);    
        }); 
}

Further information is available in the Angular Documentation .

Try this:

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

            });
    }


    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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