尝试修复CORS问题后出现Spring Boot的400问题

时间:2018-08-09 21:50:51

标签: java spring-boot

我尝试使用Spring Boot修复如下所示的CORS问题后,遇到了400错误的请求问题

  

嵌套的异常是com.fasterxml.jackson.core.JsonParseException   无法识别的令牌“ assessmentLevel”:正在期待(“ true”,“ false”   或'null')\ n在[来源:(PushbackInputStream);行:1,列:   17]“,” path“:” / assessments / createAssessment“}

CorsFilter:

public class CorsFilter extends GenericFilterBean implements Filter {

       @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setHeader("Access-Control-Allow-Headers", "*");
            response.setHeader("Access-Control-Allow-Credentials", "false");
            response.setHeader("Access-Control-Max-Age", "3600");
            filterChain.doFilter(servletRequest, servletResponse);
        }

    }

控制器:

@RequestMapping(method = RequestMethod.POST, path ="createAssessment")
@ResponseBody
public String createAssessment(@RequestBody AssessmentRequest assessmentRequest) {
    return assessmentService.addAssessment(assessmentRequest);
}

过滤器配置:

@Bean
public FilterRegistrationBean<CorsFilter> corsFilter(){
    FilterRegistrationBean<CorsFilter> registrationBean
            = new FilterRegistrationBean<>();

    registrationBean.setFilter(new CorsFilter());
    registrationBean.addUrlPatterns("/assessments/*");
    registrationBean.setOrder(1);

    return registrationBean;
}

请求的请求有效负载:

assessmentLevel=sa&assessmentSubTopic=asd&assessmentTopic=asdf&createdBy=d&rating=1

请求正文:

public class AssessmentRequest {
    private String assessmentTopic;
    private String assessmentSubTopic;
    private String createdBy;
    private String rating;
    private String assessmentLevel;
//Getter and setters
}

AJAX呼叫

$.ajax({
                url : 'http://localhost:8080/assessments/addAssessment',
                dataType : 'json',
                type : 'POST',
                contentType: "application/json",
                beforeSend : function (xhr) {
                    xhr.setRequestHeader('Accept', '*/*');
                    xhr.setRequestHeader('Content-Type', 'application/json');

                },
                data : {
                    'assessmentTopic' : $('.assessment-topic').val(),
                    'assessmentSubTopic' : $('.assessment-sub-topic').val(),
                    'createdBy' : $('.assessment-creator').val(),
                    'rating' : $('.assessment-rating').val(),
                    'assessmentLevel' : $('.assessment-level').val()
                },
                success : function (response) {
                    assessmentId = response;
                    $('.choose-file').removeClass('hidden');
                    $('.form-control').attr('disabled', true);
                    $('.create-assessment-button').attr('disabled', true);
                },
                error : function (xhr, status, error) {
                    alert('failed');
                }
            });

1 个答案:

答案 0 :(得分:0)

CORS没有问题。您在映射中使用@RequestBody,但是要发送的请求正文看起来像是请求参数的字符串。

您应该使用@RequestParam而不是@RequestBody来正确映射参数(请注意,它不会绑定到自定义对象,请参见this answer)或发送格式正确的正文按照Content-Type标头。

只有您自己知道,不可能猜测您的请求主体的外观。