SpringBoot忽略前端头信息参数Accept

/ 后端 / 没有评论 / 254浏览

看到接口错误日志发现,报错了如下信息:

org.springframework.web.HttpMediaTypeNotAcceptableException: 
Could not parse 'Accept' header ["/*]: Invalid mime type ""/*"

通过分析发现是前端的Accept传的不对,一般为客户端所支持的内容编码格式,比如application/json等,也可以为通配符如*/,但是此时前端传的确实/,目前前端也没找到原因,并且报错也是少数,于是从后端入手避免报错;

解决方案

在web配置代码中,加入以下代码即可

@Configuration
public class WebConfig implements WebMvcConfigurer {

    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.ignoreAcceptHeader(true);
        configurer.defaultContentType(MediaType.APPLICATION_JSON, MediaType.TEXT_HTML);
    }

其中configurer.ignoreAcceptHeader(true)的作用是忽略头信息中的Accept,而configurer.defaultContentType则为默认返回给前端的内容编码类型;

如果只设置默认编码类型为MediaType.APPLICATION_JSON,当接口返回的是MediaType.TEXT_HTML时则依然报406错误,如下面代码,所以需要将所需要的内容编码类型都加上:

@GetMapping(value = "/check", produces = MediaType.TEXT_HTML_VALUE)
    public String checkHtml(HttpServletRequest request) {
  ...
}