Issue
I am making a project in Angular which gets a json of users from a tomcat application running on localhost:8080. Now I'm trying to update a user using http.put. When I send my put request I get this error printed in my console:
Access to XMLHttpRequest at 'href="http://localhost:8080/Servlet?command=UpdateUser" rel="nofollow noreferrer">http://localhost:8080/Servlet?command=UpdateUser' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My servlet uses a handlerfactory which makes the right handler to handle the request. The UpdateUser handler has this code right now:
public class UpdateUser extends RequestHandler {
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Enumeration<String> params = request.getParameterNames();
System.out.println(params);
while (params.hasMoreElements()) {
String paramName = params.nextElement();
System.out.println(paramName + ":" + request.getParameter(paramName));
}
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "X-PINGOTHER,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
response.addHeader("Access-Control-Expose-Headers", "xsrf-token");
response.setStatus(HttpServletResponse.SC_ACCEPTED);
}
}
Note: I just put the while loop there so I was able to see how my content from my angular application arrived in my handler.
In the app.component.ts of my angular application I have this code to update the user:
updateUser(user): void {
this.userService.updateUser(user).subscribe();
}
This calls this method in my user.service.ts:
private httpOptions = {headers: new HttpHeaders({
'Content-Type': 'application/json'
})};
updateUser(user): Observable<User> {
return this.http.put<User>(this.updateUsersUrl, user, this.httpOptions);
}
In my network tab of my console I see that my handler gets called, but nothing is getting printed. So I figured I might need to handle my preflight request somewhere else?
Solution
Overriding the doOptions method in my servlet and setting all the headers there, seemed to solve the problem
Answered By - Mkay
Answer Checked By - Willingham (JavaFixing Volunteer)