Fixing CORS policy with Java Spring

If you’re trying to access a resource with Javascript that is on a different server than the location of your website, you probably have got a error similar to “has been blocked by CORS policy: Response to preflight request doesn’t pass access control check ” in your Javascript console when you try to make the request.

If you are using Java Spring framework, you can fix at the class level or method level by adding @CrossOrigin at the top of the class or method. Adding it before the class will apply it to all functions within the class.

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin(origins = "")
@RequestMapping(value ="/endpoint")
public class MyClass{