【问题标题】:org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported(Ajax, Spring)org.springframework.web.HttpMediaTypeNotSupportedException:不支持内容类型“application/json”(Ajax,Spring)
【发布时间】:2017-10-21 03:22:04
【问题描述】:

我尝试发送 PUT 请求。我有 serialazible 类 和具有必要设置的控制器,我的请求有 contentType: "application/json"。

FlightDto:

 public class FlightDto implements Serializable {
    private int id;
    private String navigation;

    public FlightDto() {
        super();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNavigation() {
        return navigation;
    }

    public void setNavigation(String navigation) {
        this.navigation = navigation;
    }

}

PUT 请求:

  function editNavigation() {
    var flight={
        id:idAction.replace('edit',''),
        navigation:newNavigation
    };
    console.log(flight);
    var prefix = '/airline/';
    $.ajax({
        type: 'PUT',
        url: prefix +'flights/' + idAction.replace('edit',''),
        data: JSON.stringify(flight),
        contentType: "application/json",
        success: function(receive) {
            $("#adminTable").empty();
            $("#informationP").replaceWith(receive);
            $("#hiddenLi").removeAttr('style');
        },
        error: function() {
            alert('Error edited flight');
        }
    });
}

console.log(飞行); - 对象{id:“7”,导航:“sdfdsfsd”}

飞行控制器:

   @RequestMapping(value = prefix + "/flights/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String updateFlight(@PathVariable("id") String id, @RequestBody FlightDto flightDto) {
        String returnText = "Flight edited successful";
        String str1 = flightDto.getNavigation();
        String str2 = id;
        return returnText;
    }

错误:

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported

如何解决这个错误?

【问题讨论】:

  • 您应该在 ajax 中添加 dataType: "json"。或者添加像 headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } 这样的标题

标签: java json ajax spring spring-mvc


【解决方案1】:

您需要使用 headers 属性在您的标头中定义内容类型,而不是在有效负载中

   data: JSON.stringify(flight),
   headers:{contentType: "application/json"}

【讨论】:

  • 已更改:headers:{contentType: "application/json"}。为什么我只有警报('错误编辑航班');现在?
猜你喜欢
  • 2015-11-01
  • 2015-03-26
  • 2016-11-17
  • 2022-12-22
  • 1970-01-01
  • 1970-01-01
  • 2015-06-21
  • 2019-02-20
  • 2018-08-06
相关资源
最近更新 更多