apache cors头是在 AJAX 响应中丢失,在浏览器响应中存在

daupos2t  于 2023-01-26  发布在  Apache
关注(0)|答案(1)|浏览(175)

我有一个Angular 应用程序,它可以执行跨源GET请求。基础结构如下:

browser --- nginx --- apache --- tomcat9

当我在浏览器中通过url查找页面时,它包含以下标题,firefox的网络调试器可以证明这一点:

Access-Control-Allow-Headers    Content-Type
Access-Control-Allow-Origin *

然而,当Angular 应用访问同一个页面时,响应中缺少上面的标头。无论是从本地主机访问应用,从其他主机访问应用,还是从同一个主机访问应用(在后一种情况下,当然可以工作,但标头不存在),都会出现这种情况。
有什么区别?我怎样才能得到相同的行为?是的,我可以在nginx和apache中添加头文件,但它是特定于应用程序的,我不想把它放在基础设施中。
头由Tomcat应用程序通过以下代码发出:

@WebFilter()
public class ResponseFilter implements Filter {

  private static final String CONTENT_TYPE = "Content-Type";
  private static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
  private static final String VALUE = "*";
  private static final String CORS_HEADER = "Access-Control-Allow-Origin";

  @Override
  public void doFilter(final ServletRequest request, final ServletResponse response,
      final FilterChain chain) throws IOException, ServletException {
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    httpServletResponse.setHeader(
        CORS_HEADER, VALUE);
    httpServletResponse.setHeader(
        ACCESS_CONTROL_ALLOW_HEADERS, CONTENT_TYPE);
    chain.doFilter(request, response);
  }

  @Override
  public void init(final FilterConfig filterConfig) throws ServletException {
  }

  @Override
  public void destroy() {
  }
}

Apache配置的相关部分:

ProxyPass / http://localhost:8080/
<LocationMatch /.*>
#    DirectoryIndex off
    RewriteEngine Off
    AuthType openid-connect
    AllowOverride None
    Require valid-user
</LocationMatch>

nginx配置的相关部分:

server {
listen 443 ssl;
server_tokens off;
      server_name  <server name>;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_certificate <filename>; # managed by Certbot
    ssl_certificate_key <filename>; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

  add_header Strict-Transport-Security max-age=63072000;

location / {
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Host $http_host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://<ip address>:<port>;
    }
}
zazmityj

zazmityj1#

我保留着这个答案,希望它能帮助那些和我一样忽视同样事情的人。
请求因未授权而失败,缺少cors标头只是添加在其顶部。
身份验证由Apache处理,请求甚至没有到达Tomcat,因此没有cors头。

相关问题