how to set headers to application/json in angular2

前端 未结 5 1154
难免孤独
难免孤独 2021-01-17 03:00

I am trying to send HTTP post request in Angular2 but not able to set headers to content type application JSON.

My code is:

login(url,postdata)
{
            


        
相关标签:
5条回答
  • 2021-01-17 03:26

    Angular 9 version for 2020

    export class ApiService {
    
      private headers = new HttpHeaders({
        'Content-Type': 'application/json',
      });
    
      constructor(
        private http: HttpClient) {
      }
    
      get(path: string, params: HttpParams = new HttpParams()): Observable<any> {
        return this.http.get(`${environment.apiUrl}${path}`, {params, headers: this.headers});
      }
    }
    
    0 讨论(0)
  • 2021-01-17 03:39

    You should use code like this

    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    
    let options = new RequestOptions({ headers: headers });
    return this.http.post(url, JSON.stringify(postdata), options).map(res => res.json());
    
    0 讨论(0)
  • 2021-01-17 03:40

    Try this code:

    private _getHeaders():Headers {
       let header = new Headers({
         'Content-Type': 'application/json'
       });
    
       return header;
    }
    
    
    
    public login(url, postdata){
       let options = new RequestOptions({
          headers: this._getHeaders()
       });
       return this.http.post(url, JSON.stringify(postdata),options).map(res => res.json());
    }
    
    0 讨论(0)
  • 2021-01-17 03:44

    change _http.post parameters :

    login(url,postdata) {
        var headers = new Headers({'Content-Type': 'application/json'});
        return this._http.post(url,postdata,{headers:headers})
                    .map(res => res.json())    
    }
    
    0 讨论(0)
  • 2021-01-17 03:50

    Referencing the Angular 2 Angular Http Guide @angular/http has been deprecated, and @angular/common/http should be the one you are using in your Angular 2 App. Because if you do not specify http headers the default request will be sent as Content-Type text/plain, How you modify the http headers is to:

    import { HttpClient, HttpHeaders } from '@angular/common/http';
    .....
    const req = this.http.post('/api/PostRequest/',
                                JSON.stringify(object),
                                {
                                 headers:new HttpHeaders()
                                 .set('Content-Type','application/json')
                                 }).subscribe();
    
    0 讨论(0)
提交回复
热议问题