Home > Net >  Cross origin blocked between Ajax and Spring Controller
Cross origin blocked between Ajax and Spring Controller

Time:11-19

I want a Javascript function to send data to a Spring controller and get a response. However, due to the strict-origin-when-cross-origin Referrer policy, the request does not go through.

Spring Controller :

@Controller
public class EventController {

@ResponseBody
@RequestMapping(value = "/event", method = RequestMethod.POST)
public String handleAjax(@RequestParam Integer id, HttpServletRequest request, HttpServletResponse response) {

    response.setHeader("Access-Control-Allow-Origin", "*");

    return "OK";

}
}

Javascript functions :

function getContextPath() {
return window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
}  

function move(moveDir,velocity){
$.ajax({
    type : "POST",
    url : getContextPath()    "/event",
    success: function(data){
        console.log(data)
    }
});
}

I know that I have to allow cross-origin for these files. So far, the things I tried didn't work. List of what I tried :

-> Adding @CrossOrigin(origins = "http://localhost:8081", maxAge = 3600) to the controller

-> Adding response.setHeader("Access-Control-Allow-Origin", "*"); to the controller

-> Adding crossorigin="anonymous" to the Javascript <script> tag

CodePudding user response:

Your code won't work because you specify to support POST method only

@RequestMapping(value = "/event", method = RequestMethod.POST)

OPTIONS method is required as Preflighted requests in CORS.

So you must support POST and OPTIONS also to make it work.

@RequestMapping(value = "/event")
@RequestMapping(value = "/event", method = { RequestMethod.POST, RequestMethod.OPTIONS })

https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS

CodePudding user response:

I finally got it. There were two problems.

The first was that I had to add that header to the ajax request, to allow the request to be handled by the server: headers: { 'Access-Control-Allow-Origin': '/path_to_request_target' },. Putting '*' instead of '/path_to_request_target' would also work.

The second was with my dispatcher servlet. I had to put .html at the end of the URL : url : getContextPath() "/event.html",. This is due of the mapping of my dispatcher servlet :

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/index.jsp</url-pattern>
    <url-pattern>*.html</url-pattern>
</servlet-mapping>

Adding .html to the URL worked because of <url-pattern>*.html</url-pattern>. Adding a <url-pattern> that satisfied the format of the inital URL would also work.

  • Related