加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular http post请求内容类型从’text / plain’到’applicati

发布时间:2020-12-17 17:23:40 所属栏目:安全 来源:网络整理
导读:我试图使用POST请求从服务获取数据.但我不能改变标题(TS不会编译)或内容类型.我在控制台中收到此错误: status”:415,”error”:”Unsupported Media Type”,”exception”:”org.springframework.web.HttpMediaTypeNotSupportedException”,”message”:”C
我试图使用POST请求从服务获取数据.但我不能改变标题(TS不会编译)或内容类型.我在控制台中收到此错误:

status”:415,”error”:”Unsupported Media Type”,”exception”:”org.springframework.web.HttpMediaTypeNotSupportedException”,”message”:”Content type ‘text/plain’ not supported”

下面是我的组件代码.

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

注意:使用了代码段,因为格式化不会让我发布为pre.

使用最新的角度4版本.
还应正确配置服务器,仅接受json数据.
我尝试了Angular文档中的示例,但没有一个工作.

任何人都知道如何让它工作?
提前致谢.

解决方法

在您的示例中(以及在注释中),由angular提供的两个不同的http实现被混合.由于’@ angular / common / http’的角度4 HttpClient可用,因此是推荐的方法.由于角度为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”中的所有依赖项.只要您使用此模块中的对象,您的代码就会出现问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读