【问题标题】:Unsupported Media Type","exception":"org.springframework.web.HttpMediaTypeNotSupportedException","message":"Content不支持的媒体类型","异常":"org.springframework.web.HttpMediaTypeNotSupportedException","消息":"内容
【发布时间】:2017-12-02 00:23:32
【问题描述】:

我有一个带有以下 Post 代码的 RestController,并尝试在我的 AJAX 中使用它来在数据库表中添加数据。我有以下错误。

RestController 方法发布

@RequestMapping(method = RequestMethod.POST)
    public void create(@RequestBody MessageChat chatmessage) {
        messageService.save(chatmessage);

    }

Ajax 调用

$( "#vut" ).on( "click", function(e){
     e.preventDefault();
        e.stopPropagation();
        $.ajax({
               url: '/messagechat',
               method: 'POST',ContentType:'application/json',dataType: 'JSON',
               data: {
                      message: 'a'
                  }
                })

    });

错误

{"timestamp":1498660502132,"status":415,"error":"Unsupported Media Type","exception":"org.springframework.web.HttpMediaTypeNotSupportedException","message":"Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported","path":"/messagechat"}

有人可以帮忙吗?

【问题讨论】:

    标签: java hibernate rest spring-boot


    【解决方案1】:

    应该是

    $( "#vut" ).on( "click", function(e){
        e.preventDefault();
        e.stopPropagation();
        $.ajax({
               url: '/messagechat',
               method: 'POST',
               dataType: 'json',
               data: JSON.stringify({message: 'a'})
        });
    });
    

    在你的控制器中:

    @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void create(@RequestBody MessageChat chatmessage) {
        messageService.save(chatmessage);
    
    }
    

    【讨论】:

    • 感谢您的回答,我试过了,但有错误消息":"Content type 'application/json' not supported","path":"/messagechat"
    • 工作正常。谢谢你:D
    【解决方案2】:

    尝试“contentType”而不是“ContentType”

    【讨论】:

    • 感谢您的回答,我试过了,但有错误消息":"Content type 'application/json' not supported","path":"/messagechat"
    【解决方案3】:

    根据documentation of jQuery's function ajax(),您应该将属性名称从ContentType 更改为contentType。 Javascript 标识符不区分大小写。

    【讨论】:

    • 感谢您的回答,我试过了,但有错误消息":"Content type 'application/json' not supported","path":"/messagechat"
    【解决方案4】:

    试试

    @RequestMapping(method = RequestMethod.POST, headers = "Accept=*/*)
    

    您也可以将其设置为 headers="Accept=application/json"

    【讨论】:

      猜你喜欢
      • 2017-10-21
      • 2021-04-19
      • 2015-11-01
      • 2015-03-26
      • 2014-09-18
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 2019-02-25
      相关资源
      最近更新 更多