Each time I call the Ajax PUT call to my service, it returns the following error:
XMLHttpRequest cannot load http: // localhost: 8080 / users / edit . The response to the request before the flight does not pass the access control check. There is no "Access-Control-Allow-Origin" header on the requested resource. Origin ' http: // localhost: 63342 ', therefore not allowed. The response had an HTTP status code of 403.
After 2 days of investigation, I tried to execute the following decision 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 dispatchOptionsRequest:
public abstract class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected void customizeRegistration(ServletRegistration.Dynamic registration) { registration.setInitParameter("dispatchOptionsRequest", "true"); super.customizeRegistration(registration); } }
A controller to handle the entire 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 am I doing wrong with the configuration?
java spring ajax spring-mvc cors
daniegarcia254
source share