【问题标题】:angular v5.1.0 HttpClient not set header content-type : application/jsonangular v5.1.0 HttpClient 未设置标头内容类型:application/json
【发布时间】:2017-12-15 11:19:38
【问题描述】:

我正在尝试将 post api 的标头设置为 application.json

let options: { headers?: {'Content-Type':'application/json'} }

但未设置。

【问题讨论】:

  • @MarkHim 请不要添加无用的无用 cmets,例如“代码格式化”。直接回答吧。

标签: angular httpclient


【解决方案1】:

要使用新的 HttpClient 类定义内容类型,您需要:

  1. @angular/common/http 导入(而不是从当前标记为已弃用的 @angular/http 导入)
import { HttpClient, HttpHeaders } from '@angular/common/http';
  1. 在构造函数中注入HttpClient
constructor(private http: HttpClient) { }
  1. 定义一个私有字段 headers 来定义所需的内容类型,并定义一个 options 来准备您将在通话中使用的对象:
private options = { headers: new HttpHeaders().set('Content-Type', 'application/json') };
  1. 在你的方法中使用它:
this.http.post('your target url', yourBodyObject, this.options)

其中'your target url'yourBodyObject 仅用作示例,需要替换为您的真实数据。

【讨论】:

    【解决方案2】:

    Angular 文档中有一个关于此的部分 - 可能是最近添加的:

    import { HttpHeaders } from '@angular/common/http';
    
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
        'Authorization': 'my-auth-token'
      })
    };
    

    当我尝试使用上述格式向 httpOptions 添加响应类型时,TypeScript 给了我警告,所以我成功地使用了以下内容:

    let headers = new HttpHeaders({
                'Content-Type': 'application/text'
            });
    
    return this.http.get(url, { responseType: 'text', headers })
    

    文档link

    【讨论】:

      【解决方案3】:

      检查一下,

      import {Http, Response, Headers, RequestOptions} from "@angular/http";  
      

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

      用于 Http 调用。

      【讨论】:

      • 您提供的导入是针对“Http”而不是针对“HttpClient”类的。
      【解决方案4】:

      在这里试试这个代码=>

      let header = {'Content-Type':'application/json'}
      

      【讨论】:

        【解决方案5】:

        这是一个例子:

        public _funName( _params ): Observable<void> {
            const headers = new Headers( { 'Content-Type': 'application/json' }  // set your header);
            /* The option withCredentials: true in the code bellow is used with the CORS variables, that is when the REST functions are on another server then Node.js and the Angular2 development application. */
        
            const options = new RequestOptions( { headers: headers, withCredentials: true } );
        
            return this.http.post( _yourLink, _params, options )
            .map( this.extractData )
            .catch( this.handleError );
        }
        
        
        
        public extractData( res: Response ) {
            const body = res.json();
            // const body = res;
            return body || {};
        }
        
        public handleError( error: Response | any ) {
            let errMsg: string;
            if ( error instanceof Response ) {
                const body = error.json() || '';
                const err = body.error || JSON.stringify( body );
                errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
            } else {
                errMsg = error.message ? error.message : error.toString();
            }
            console.error( errMsg );
            return Observable.throw( errMsg );
        }
        

        希望对你有帮助。

        【讨论】:

        • 此示例适用于“Http”类,而不是“HttpClient”
        【解决方案6】:

        我们可以通过创建新的 HttpHeaders 对象来定义请求头。

        HttpHeaders 对象本质上是不可变的。因此,将所有标题详细信息设置在同一行中。

        getUser(name: string, age: string) {
            const params = new HttpParams().set('name', name).set('age', age);
        
            const headers = new HttpHeaders()
              .set('Content-Type', 'application/json')
              .set('Authorization', 'my token');
        
            return this.http
              .get(`${endPoint}/user`, {
                params,
                headers
              });
          }
        

        【讨论】:

          【解决方案7】:
          let hdr = {
                  'Content-Type': 'application/json'
              };
          let options = { headers: hdr };
          this.httpClient.post(url, payloadData, options);
          

          【讨论】:

            【解决方案8】:

            操作码sn-p:

            let options: { headers?: {'Content-Type':'application/json'} }
            

            正在定义一个 type { headers?: {'Content-Type':'application/json'} } 的选项变量,它是有效的,但不是你想要的。将: 更改为= 以使其成为assignment,并删除了对分配无效的?。这是合法的,最接近 OP 的尝试,并且应该有效:

            let options = { headers: {'Content-Type':'application/json'} };
            

            【讨论】:

              【解决方案9】:

              如果您使用的是http.put(),请使用以下代码并接收 json/纯文本:

              const httpOpt = {
                headers: new HttpHeaders({
                  'Content-Type': 'application/json',
                  'Accept': 'application/json, text/plain'
                })
              };
              
              this.http.put('http://localhost:8080/bookapi/api/book/'+id, JSON.stringify(requestObj), httpOpt);
              

              【讨论】:

                【解决方案10】:

                这就是我在 user.service.ts 中获取用户详细信息的方式

                进口:

                import {HttpClient, HttpHeaders} from '@angular/common/http';
                import {Observable} from 'rxjs/Observable'; 
                import {Injectable} from '@angular/core';
                

                在类中声明变量:

                @Injectable()
                export class UserService {
                
                private httpHeaders = new HttpHeaders().set('Content-Type','application/json');
                protected options = {headers: this.httpHeaders,
                    search:{}
                };
                
                constructor(private http: HttpClient) {
                
                    }
                
                /**
                 * getting user details
                 * @returns {Observable<any>}
                 */
                getUser(): Observable<any>{
                    return this.http.get('userApi/').catch(err => this.errorHandler(err));
                }
                
                /**
                 *
                 * @param error
                 * @returns {any}
                 */
                errorHandler(error: any): any {
                    if (error.status < 400) {
                        return Observable.throw(new Error(error.status));
                    }
                  }
                }
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2021-08-25
                  • 1970-01-01
                  • 1970-01-01
                  • 2018-04-19
                  • 1970-01-01
                  • 2012-02-28
                  • 2017-04-27
                  • 2018-08-28
                  相关资源
                  最近更新 更多