I have a theoretical doubt on CORS implementation.
A way to enable cross-origin requests is to set a specific Header on the response:
private void setAccessControlHeaders(HttpServletResponse resp) {
resp.setHeader("Access-Control-Allow-Origin", "http://www.allowed.domain.com");
resp.setHeader("Access-Control-Allow-Methods", "POST");
}
My question is: if I set the header in the response (which is at the end of the request-response chain), it means the request I receive is already processed, side effects are caused, and then the program decides if the response must be sent back or not, based on the presence of this header in the response.
For example:
public class MyServlet extends HttpServlet {
//...
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws Exception{
Order order = (Order) parseBodyRequest(req);
orderRepository.save(order); //if I check the allowed domains later, I can get serious side effects!
resp.setHeader("Access-Control-Allow-Origin","http://www.allowed.domain.com");
resp.getWriter().println("Order n."+ order.getId()+ "has been saved successfully!");
}
}
In the example above, the order is parsed and saved into the database before even checking if the domain from which the request comes is allowed or not.
This thing seems absurd, so how does it work in reality?