David
David

Reputation: 398

CORS enabled on Java Servlet yet receiving CORS error from frontend

I am writing a web application where the client posts (JSON) form data to the and the server should also respond with a JSON. The server-side is written using java servlets, running on Tomcat and the client is written in Angular 7. Unfortunately, I am facing a CORS error even after enabling cors via the HTTP headers. Is there anything I am missing?

This is the error I get on the client side: Access to XMLHttpRequest at 'http://localhost:8080/mysocial/signIn' 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.

I have read the following posts and tried each of the solutions but the problem still persists: CORS enabled but still getting CORS error

How to fix CORS issue http request in Angular 5

As I have said I have enabled the CORS headers. The code snippets show my server side and client side code:

// From my data service (client-side angular 7)
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private baseUrl: string = "http://localhost:8080/mysocial";
  private http: HttpClient;

  constructor(http: HttpClient) { 
    this.http = http;
  }

  public authenticateLogin(username: string, password: string) //: boolean
  {
    let url: string = `${this.baseUrl}/signIn`;
    let header = new HttpHeaders({'Accept': 'application/json' ,'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
    let httpOptions = { headers: header };
    let body = {username: username, password: password};

    return this.http.post(url, body, httpOptions).subscribe(
      (response) => console.log(response),
      (err) => console.log(err)
    );
    //return true;
  }
}

Server-side code:

// server-side java servlets code
   private void configResponse(HttpServletResponse response)
   {
      response.setContentType("application/json");
      response.addHeader("Access-Control-Allow-Origin", "http://localhost:4200");
      response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
   }

   public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
   {
      Model model = (Model) getServletContext().getAttribute("model");
      String username = request.getParameter("username");
      String password = request.getParameter("password");

      configResponse(response);
      PrintWriter out = response.getWriter();

      if (model.validateLoginDetails(username, password))
      {
         String firstName = model.getUserInfo("firstName", "username", username);
         int id = Integer.parseInt(model.getUserInfo("id", "username", username));

         HttpSession session = request.getSession();
         session.setMaxInactiveInterval(60);
         session.setAttribute("username", username);
         session.setAttribute("firstname", firstName);
         session.setAttribute("id", id);

         JsonObject value = createJsonResponse(username, password, true);
         out.println(value);
      }
      else
      {
         JsonObject value = createJsonResponse(username, password, false);
         out.println(value);
      }
   }

I expect the server to send a JSON back to the client but I'm getting a CORS error from the client.

Upvotes: 3

Views: 3439

Answers (1)

David
David

Reputation: 398

Just for completeness and for anyone who may come across this problem, I was able to solve this problem using the tomcat filters provided here: http://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#CORS_Filter (shown by sideshowbarker (https://stackoverflow.com/users/441757/sideshowbarker))

There had to change some server configurations first to match the filter. I'd suggest customizing the filter to your needs.

Upvotes: 2

Related Questions