使用Spring Framework为OPTIONS请求启用CORS [英] Enable CORS for OPTIONS request using Spring Framework

查看:3935
本文介绍了使用Spring Framework为OPTIONS请求启用CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我对我的服务进行PUT Ajax调用时,它会返回以下错误:


XMLHttpRequest无法加载 http:// localhost:8080 / users / edit 。对预检请求的响应不通过访问控制检查:在请求的资源上不存在Access-Control-Allow-Origin头。原因 http:// localhost:63342 因此不允许访问。该响应的HTTP状态代码为403.


经过2天的调查,我已达到尝试下面的解决方案。



这是 主类 ,我加载必要的类并运行应用程序:

  @SpringBootApplication 
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {

public static void main String [] args){
SpringApplication.run(Application.class,args);
}

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application){
return application.sources(DispatcherServletInitializer.class,OptionsController.class,Application.class);
}
}

DispatcherServilet initializer ,其中我启用了dispatchOptionsRequest:

  public abstract class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration){
registration.setInitParameter(dispatchOptionsRequest,true);
super.customizeRegistration(registration);
}
}

A > 用于处理所有OPTIONS请求:

  @Controller 
public class OptionsController {

@RequestMapping(method = RequestMethod.OPTIONS)
public HttpServletResponse句柄(HttpServletResponse the HttpServletResponse)throws IOException {
theHttpServletResponse.addHeader(Access-Control-Allow-Headers,origin,content-type ,accept,x-requested-with);
HttpServletResponse.addHeader(Access-Control-Max-Age,60);
HttpServletResponse.addHeader(Access-Control-Allow-Methods,GET,POST,PUT,DELETE,OPTIONS);
HttpServletResponse.addHeader(Access-Control-Allow-Origin,*);
return theHttpServletResponse;
}

}



自定义初始值设置是自定义初始值设置类真的解决了我的问题。由于实施了 optionsController ,因此OPTIONS请求失败。



因此我删除了 optionsController ,并且只需在我的Rest Controller中为OPTIONS请求添加 handle 方法,问题就解决了:

  @CrossOrigin(origins =*,maxAge = 3600)
@RestController
@RequestMapping(/ users)
public class Users {

@RequestMapping(
value =/ edit,
method = RequestMethod.PUT)
public ResponseEntity<?> create(@RequestBody User user){
....
....
}

@RequestMapping(
value =/ ** ,
method = RequestMethod.OPTIONS

public ResponseEntity handle(){
return new ResponseEntity(HttpStatus.OK);
}
}


Every time I make a PUT Ajax call to my service, it return the following error:

XMLHttpRequest cannot load http://localhost:8080/users/edit. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. The response had HTTP status code 403.

After 2 days of investigation, I've reached to try the next solution on my code.

This is the main class where I load the necessary classes and run the application:

@SpringBootApplication
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer{

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(DispatcherServletInitializer.class, OptionsController.class,Application.class);
    }
}

The DispatcherServilet initializer, where I enable the dispatchOptionsRequest:

public abstract class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration) {
        registration.setInitParameter("dispatchOptionsRequest", "true");
        super.customizeRegistration(registration);
    }
}

A controller for handle all OPTIONS request:

@Controller
public class OptionsController {

    @RequestMapping(method = RequestMethod.OPTIONS)
    public HttpServletResponse handle(HttpServletResponse theHttpServletResponse) throws IOException {
        theHttpServletResponse.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with");
        theHttpServletResponse.addHeader("Access-Control-Max-Age", "60"); 
        theHttpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        theHttpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
        return theHttpServletResponse;
    }

}

What I'm doing wrong with the configuration?

解决方案

Finally, the DispatcheServlet customize initializer was the class that really solved my problem. The OPTIONS request was failing because of the optionsController I had implemented, it was wrong.

So I removed that optionsController, and just by adding the handle method in my Rest Controller for the OPTIONS request, the problem was solved:

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/users")
public class Users {

    @RequestMapping(
            value = "/edit",
            method = RequestMethod.PUT)
    public ResponseEntity<?> create(@RequestBody User user){
         ....
         ....
    }

    @RequestMapping(
            value = "/**",
            method = RequestMethod.OPTIONS
    )
    public ResponseEntity handle() {
        return new ResponseEntity(HttpStatus.OK);
    }
}

这篇关于使用Spring Framework为OPTIONS请求启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆