Issue
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
Solution
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.
Answered By - nico263nico