【问题标题】:Cannot convert data to json in angular 13 Content type 'text/plain;charset=UTF-8' not supported] after sending data from angular to spring boot在将数据从角度发送到弹簧启动后,无法将数据转换为角度 13 中的 json 内容类型'text/plain;charset=UTF-8' not supported]
【发布时间】:2022-01-19 19:29:14
【问题描述】:

我正在尝试通过以下方式提交表单:

saveBuildcompany(): void {
    // @ts-ignore

  
    // @ts-ignore
    console.log(this.group?.value);
    
   let data2=this.group.value;
    let serializedForm = JSON.stringify(data2);

   console.log(data2);
   // data2.sociallinks.stringify;
    this.buildcompanyService.create(serializedForm)
      .subscribe({
        next: (res) => {
          console.log(res);
          this.submitted = true;
        },
        error: (e) => console.error(e)
      });
  }

服务如下:

create(data: any): Observable<any> {
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');
    return this.http.post(baseUrl+"/add", data, {headers: headers});
  }

毕竟我得到了标题中的异常。我做错了什么?

【问题讨论】:

  • 你能把你的例外贴在这里吗?

标签: json angular spring-boot angular13


【解决方案1】:

如果您要发送表单数据,请将“Content-Type”更改为 application/x-www-form-urlencoded 和“Accept”application/json

create(data: any): Observable<any> {
    let headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'});
    return this.http.post(baseUrl+"/add", data, {headers: headers});
  }

create(data: any): Observable<any> {
    let headers = new HttpHeaders();
    headers.set('content-type', 'application/x-www-form-urlencoded')'
...
    return this.http.post(baseUrl+"/add", data, {headers: headers});
  }

【讨论】:

  • 没有帮助。例外还是一样。
  • 好吧,我没有在昨天发表评论,抱歉。问题只是在某种程度上我正在创建 http headers 变量。我正在使用在堆栈中某处找到的追加,实际上并没有更改响应中的标题。答案中提供的代码就是这样做的。实际的 api 应用只支持 JSON。
【解决方案2】:

您可以将 "Content-Type" 更改为 application/x-www-form-urlencoded"Accept" application /json。试试下面的代码片段。

create(data: any): Observable<any> {
    let headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'});
    return this.http.post(baseUrl+"/add", data, {headers: headers});
  }

【讨论】:

    【解决方案3】:

    只是总结一下我在上面的所有悲伤。实际的创建函数是这样的。这是发送正确的标头信息:

    create(data: any): Observable<any> {
        let headers = new HttpHeaders({'Content-Type': 'application/json', 'Accept': 'application/json'});
        return this.http.post(baseUrl+"/add", data, {headers: headers});
      }
    

    【讨论】:

      猜你喜欢
      • 2023-02-06
      • 2023-02-15
      • 2021-04-16
      • 2014-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      相关资源
      最近更新 更多