【问题标题】:Problem whith cors response (POST application/json). 400 bad requestcors 响应问题(POST 应用程序/json)。 400 错误请求
【发布时间】:2019-02-08 19:19:17
【问题描述】:

我有代码:

1) ajax

addFarmByPost = (e) => {
        e.preventDefault();
        alert(JSON.stringify(this.state));
        fetch("http://localhost:8080/farms", {
            method: "POST",
            headers: {
                'Content-Type': 'application/json'
            },

            data: JSON.stringify(this.state)
        })
    }

2) 休息控制器

 @PostMapping("/farms")
    public ResponseEntity<Object> addFarm(@RequestBody String farmParam) {...//do }

3) Spring Boot 应用中的 Clobal cors 配置:

**@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter(){
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedMethods("POST", "GET", "PUT", "DELETE", "OPTIONS")
                        .allowedOrigins("*")
                        .allowedHeaders("*")
                        .allowCredentials(false)
                        .maxAge(6000);

            }
        };
    }**

但是当我发出 ajax POST 请求(应用程序/json) 时,我遇到了异常 400 错误请求。和异常:处理程序执行:org.springframework.http.converter.HttpMessageNotReadableException:缺少所需的请求正文。

获取 CORS 方法效果很好。我该如何解决它和 了解错误的原因。Ty。

【问题讨论】:

  • 问题不在于 cors,如异常指示(缺少必需的请求正文)问题是 spring 找不到要解析的请求正文。以及为什么将正文用作字符串??
  • Abdou Rayes,我使用字符串是因为我需要获取两个 java 对象。我可以说,当我在我的应用程序中不使用 cors 时,这种配置效果很好。
  • 你能把content-type header改成application/text吗
  • 尝试将标头设置为text/plain,因为将标头设置为application/json会导致spring寻找相应的正文阅读器(大部分时间是Jackson)并尝试转换它到您的目标类型,在这种情况下它是String.class,这将导致错误(我想,因为在这种情况下我不知道this.state 的内容)

标签: java spring spring-boot post cors


【解决方案1】:

这里的异常data: JSON.stringify(this.state)必须是body: JSON.stringify(this.state) 因为我使用 reactJS,所以我必须在 ajax 请求中写 body 而不是 data 类型

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 2018-07-08
    • 2015-04-28
    相关资源
    最近更新 更多