【问题标题】:HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supportedHttpMediaTypeNotSupportedException:不支持内容类型 'application/x-www-form-urlencoded;charset=UTF-8'
【发布时间】:2022-01-19 19:04:50
【问题描述】:

我正在尝试使用 ajax 将 javascript 发布到 spring 控制器


    $("#crear").click(function () {
        var user = document.getElementById("user").value;
        var client = document.getElementById("client").value;
        var documents = document.getElementById("documents").value;
        if (user==null||client==null||documents==null){
            document.getElementById("error").innerHTML='FALTAN COSASsssssssssss';
            alert('Rellene todo los campos!')
        }
        const data={
            fecha_inicio:'A',
            id:'A',
            fecha_entrega:'A',
            usuario:{
                nombre:user
            },
            cliente: {
                nombre:client
            }
        }
        $.ajax({
            url: urlCrearAlta,
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: data,
            success: function(data) {
                // ...
            }

        });
        $.post(urlCrearAlta,JSON.stringify(data),function (data,satus){
            console.log('${data} and status is ${status}')
        });
        document.getElementById("error").innerHTML=user+client+documents;
    });

和java代码

@RequestMapping("/altas")
@RestController
public class AltaRestController {

    private AltaController altaController;

    public AltaRestController(AltaController altaController) {
        this.altaController = altaController;
    }
@PostMapping("/create-alta")
    public void createAlta(@RequestBody AltaDTO altaDTO) {
        altaController.createAlta(altaDTO);
    }

我收到错误已解决 [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]

当我使用 $.ajax 时它不发送任何请求,只是当我使用 $.post 时它发送请求

【问题讨论】:

    标签: javascript java


    【解决方案1】:

    问题似乎是您如何使用$.post 方法。如果您不指定另一个 contentType,jQuery 默认在 post 上使用 application/x-www-form-urlencoded;charset=UTF-8 contentType。结合后端的@RequestBody 注解(默认需要application/json)会导致看到的异常和415状态码。

    这个问题的解决方案应该是相当简单的,只需为 .post 方法添加正确的配置,如下所示:

    $.post({
            url: urlCrearAlta,
            type: "POST",
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify(data)
        })
        .done((data, status) => {
              console.log(data, status);
              //do whatever you like with data and status
        });
    

    另外,正如 jQuery 文档 here 中所述,$.post 只是 $.ajax 的简写方法,所以如果 $.ajax 不起作用而 $.post 起作用,那么您的方式应该有问题配置请求或如何处理回调方法。对我来说主要的嫌疑人是你在$.ajax请求中指定的success函数,检查那里没有错,或者只是使用其他回调方法,如.done.fail.always

    【讨论】:

    • 现在的请求似乎可以正常工作,但现在我有那个错误:从源 'localhost:63343' 访问 XMLHttpRequest 已被 CORS 策略阻止:对预检的响应请求未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。浏览器控制台中的错误。坦克为你解答
    • 发生这种情况是因为现在浏览器正在对后端服务进行预检调用(选项调用),您可以从网络选项卡中看到它。由于您的后端服务没有使用正确的 Access-Control-Allow-Origin 标头响应该调用(或我猜的任何其他请求),因此浏览器会阻止该请求,并且您会在控制台中收到该异常。此行为在here 进行了详细描述,并有望防止跨源请求攻击。
    • 问题是您正在从后端的不同主机为前端应用程序提供服务。异常提到您从localhost:63343 为前端提供服务,而后端应用程序在localhost:8080。一个简单的解决方案是直接从后端应用程序为前端提供服务,或者在 spring 应用程序中启用 CORS(按照说明here 了解如何)
    猜你喜欢
    • 1970-01-01
    • 2016-02-21
    • 2020-04-13
    • 2019-11-13
    • 2018-07-24
    • 2015-11-01
    • 2015-03-26
    • 1970-01-01
    • 2020-04-21
    相关资源
    最近更新 更多