![](/img/trans.png)
[英]How do I POST/PUT JSON to a REST API endpoint without specifying Content-Type: application/json header
[英]POST request to Activiti REST API causes CORS issue when using Content-Type:application/json
我正在使用AngularJS消耗Activit REST资源。 所有GET操作均按预期方式工作,但是当我尝试使用Content-Type:application / json POST到/ runtime / process-instances时,它在预检中失败。 如您所见,响应头中没有“ Access-Control-Allow-Origin”。
例如,当我将Content-Type更改为application / x-www-form-urlencoded; charset = utf-8时,响应标头中会出现“ Access-Control-Allow-Origin”,但据我们所知,我的POST赢得了API无法正常工作,因为它希望它具有content-type:application / json
我该如何解决这个问题?
感谢任何输入!
从Activiti 5.17开始,Activiti使用Spring Security来保护REST-API。 仅当您发送在Tomcat CORS-Configuration的allowed-headers字段中传播的标头时,才会触发Tomcat CORS-Filter。 我没有成功在每个请求上触发CORS过滤器。 因此,我这样做是这样的:
编写自己的CORS过滤器
公共类CorsFilter扩展了OncePerRequestFilter {
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { response.setHeader("Access-Control-Allow-Origin", "*"); if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) { response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); response.setHeader("Access-Control-Allow-Headers", "accept, x-requested-with, Content-Type, Accept-Language, Accept-Encoding ,Origin, Access-Control-Request-Method ,Access-Control-Request-Headers, Last-Modified, Cookie, Referer"); response.setHeader("Access-Control-Expose-Headers", "Access-Control-Allow-Origin,Accept-Ranges,Content-Encoding,Content-Length,Content-Range"); response.setHeader("Access-Control-Max-Age", "100"); } filterChain.doFilter(request, response); } }
在activiti-rest-webapp2的Spring Configuration中添加过滤器:
http.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class)
和.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
选项请求需要在没有spring身份验证的情况下进行传递,因为否则,CORS预检请求将失败。
如果您这样做,Activiti将在您发出的每个请求上添加Access-Control-Allow-Origin。
最好的问候本
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.