在Java Servlet上启用了CORS,但仍从前端接收到CORS错误

时间:2019-07-05 00:46:01

标签: java tomcat cors preflight

我正在编写一个Web应用程序,客户端将(JSON)表单数据发布到,服务器也应使用JSON进行响应。服务器端是使用Java Servlet编写的,并在Tomcat上运行,而客户端则是用Angular 7编写的。不幸的是,即使通过HTTP标头启用cors后,我也遇到了CORS错误。我有什么想念吗?

这是我在客户端遇到的错误: 从源“ http://localhost:8080/mysocial/signIn”对“ http://localhost:4200”处XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:无“ Access-Control-Allow-Origin”标头存在于请求的资源上。

我已阅读以下帖子并尝试了每种解决方案,但问题仍然存在: CORS enabled but still getting CORS error

How to fix CORS issue http request in Angular 5

正如我所说,我已启用CORS标头。代码段显示了我的服务器端和客户端代码:

// 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 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);
      }
   }

我希望服务器将JSON发送回客户端,但是从客户端收到CORS错误。

1 个答案:

答案 0 :(得分:0)

仅出于完整性考虑,对于可能遇到此问题的任何人,我都可以使用此处提供的tomcat过滤器解决此问题:http://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#CORS_Filter(由sideshowbarker(https://stackoverflow.com/users/441757/sideshowbarker显示))

必须首先更改一些服务器配置以匹配过滤器。我建议根据您的需求定制过滤器。