【问题标题】:Angular http post request content type from 'text/plain' to 'application/json'Angular http post 请求内容类型从“text/plain”到“application/json”
【发布时间】:2018-03-22 00:44:04
【问题描述】:

我正在尝试使用 POST 请求从服务中获取数据。但我无法更改标题(TS 不会编译)或内容类型。我在控制台中收到此错误:

status":415,"error":"Unsupported Media Type","exception":"org.springframework.web.HttpMediaTypeNotSupportedException","message":"不支持内容类型'text/plain'"

下面是我的组件代码。

import { Component, OnInit } from '@angular/core';
import { Http, Headers, Response, URLSearchParams } from '@angular/http';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {

  searchValue: any = '';

  constructor(private http: HttpClient) { }

  getData() {

    this.http.post('MY URL',
    JSON.stringify({
      "q": "Achmea"
    }))
    .subscribe(
    data => {
      alert('ok');
      console.log(data);
    }
    )

注意:使用代码 sn-p 因为格式不允许我发布为 pre。

使用最新的 Angular 4 版本。 服务器也应该正确配置,只接受 json 数据。 我尝试了 Angular 文档中的示例,但没有一个有效。

有人知道如何让它工作吗? 提前致谢。

【问题讨论】:

    标签: angular http post request


    【解决方案1】:
    deleteWithDescription(questionFileId: number, description: string): Observable<any> {
        const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
        return this.httpClient.post(this.baseUrl + '/DeleteWithDescription/' + questionFileId, JSON.stringify(description), { headers: headers });
    }
    
    
    addExams(examId: number, questionsToInsert: QuestionDTO[]) {
        return this.httpClient.post<number[]>(this.baseUrl + '/DeleteAndInsertExams/' + examId, questionsToInsert);
    }
    

    【讨论】:

      【解决方案2】:
      const httpOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json'
        })
      }
      

      这个工作在角度

      【讨论】:

        【解决方案3】:

        我遇到了类似的问题,并且能够使用 HttpInterceptor 解决它。下面的示例应查找内容类型为“text/plain”的任何 Http 请求,并将类型转换为“application/json”以及转换正文 json。任何其他内容类型都应保留。

        import { Injectable } from '@angular/core';
        import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent } from '@angular/common/http';
        import { Observable } from 'rxjs';
        
        @Injectable()
        export class ContentTypeInterceptor implements HttpInterceptor {
        
          public constructor() {}
        
          intercept(
            req: HttpRequest<any>,
            next: HttpHandler
          ): Observable<HttpEvent<any>> {
            const ct = req.detectContentTypeHeader();
            return ct != null && ct.startsWith('text/plain')
                ? next.handle(req.clone({
                        setHeaders: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(req.body)
                    }))
                : next.handle(req);
          }
        }
        

        顺便说一句,在我的实际实现中,我使用了白名单(即 api),所以我不会意外修改我不打算修改的请求!

        【讨论】:

          【解决方案4】:

          我得到了它与 httpClient 和下面的代码一起工作:

          const postUrl = this.config.baseUrl + '/Save/' + username;
              const headers = new HttpHeaders();
              headers.append('Content-Type', 'application/json');
              headers.append('Accept', 'application/json');
              return this.http.post<string>(postUrl, '', {headers: headers});
          

          【讨论】:

            【解决方案5】:

            在您的示例中(以及在 cmets 中),由 angular 提供的两种不同的 http 实现混合在一起。由于 '@angular/common/http' 的 angular 4 HttpClient 可用并且是推荐的方式。从 Angular 5 开始,来自 '@angular/http' 的旧 Http 甚至被标记为已弃用。

            为了防止来自后端的异常消息,您必须按以下方式设置标头:

            const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
            return this.httpClient.post<T>(this.httpUtilService.prepareUrlForRequest(url), body, {headers: headers})
            ...
            

            请从您的代码中的“@angular/http”中删除所有依赖项。只要您使用此模块中的对象,您的代码就会出现问题。

            【讨论】:

              【解决方案6】:

              最好的方法是创建一个名为 http-config.ts 的文件并在下面插入代码

              import {Headers} from '@angular/http';
              
              export const contentHeaders = new Headers();
              contentHeaders.append('Accept', 'application/json');
              contentHeaders.append('Content-Type', 'application/json');
              

              然后在你的服务类中

              import {Http, RequestOptions, Headers, Response} from "@angular/http";
              @Injectable()
              export class MyService {
               url:string = '<paste your url here>'
               getData(id: string): Observable<any> {
                 let options = new RequestOptions({headers: contentHeaders});
                 return this.http
                  .get(this.url, options)
                  .map(this.extractData)
                  .catch(this.handleError);}
               }
              

              在你的组件中

                 constructor(private myService: MyService){}
              
                 private subscription: Subscription;
                 getData(popId: string) {
                 this.subscription = this.myService.getData()
                 .subscribe(
                  (data: any) => {
                    console.log(data);
                  },
                  error => {
                    console.log(error);
                  });
                }
              

              希望有帮助。

              【讨论】:

              • 这也行不通。这部分关于服务的部分在 vsc 中得到了完全强调。 return this.http .get(this.url, options) .map(this.extractData) .catch(this.handleError); 以及组件页面上的 this.myService 时
              • 实际上,您必须将服务注入到您的组件中。我更新了我的答案。如果您仍然遇到任何错误,请在此处发布
              • 我在 vsc 中遇到了一个错误,它没有让代码在组件中的该部分进行编译:this.myService.getData() 我对 Angular 非常陌生,我什至不确定在这种情况下我的 URL 应该放在哪里。我真的很想用一种非常简单的方法来完成这项工作。
              • 您可以将 URL 放在服务本身中。我更新了代码。你也可以粘贴你在 cmets 中得到的错误
              【解决方案7】:

              使用标题:

              var headers = new Headers({
                  "Content-Type": "application/json",
                  "Accept": "application/json"
              });
              
              this.http.post(this.oauthUrl, JSON.stringify(postData), {
                  headers: headers
              })
              

              【讨论】:

              • [ts] Argument of type '{ headers: Headers; }' is not assignable to parameter of type '{ headers?: HttpHeaders; observe?: "body"; params?: HttpParams; reportProgress?: boolean; respons...'. Types of property 'headers' are incompatible. Type 'Headers' is not assignable to type 'HttpHeaders'. Property 'headers' is missing in type 'Headers'. 这是我的 Visual Studio 代码在标题行中所说的内容并且不会编译..
              • 检查是否将其添加到导入中:import { Http, Headers, Response, RequestOptions, ResponseContentType } from '@angular/http';
              • 不,这也行不通。我也将它们导入了...我在 stackoverflow 上看到的与此相关的每个答案都在标题部分对我造成了影响。
              • 我看到你使用了 headers:Headers 而不是 var headers。
              • 我复制了你放在这里的代码,没有改变标题部分,只改变了url。
              猜你喜欢
              • 2015-09-07
              • 2015-06-08
              • 1970-01-01
              • 2019-08-01
              • 2012-12-16
              • 2013-06-28
              • 1970-01-01
              • 2015-02-18
              • 2021-07-27
              相关资源
              最近更新 更多