球衣跨域请求 [英] jersey cross domain request

查看:119
本文介绍了球衣跨域请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jersey 2.18开发rest api. (使用tomcat容器)

I am using jersey 2.18 for developing rest api. (using tomcat container)

我想允许从其他域访问客户端.

I want to allow access to clients from other domain.

所以我正在尝试下面的代码,以允许跨域请求.

So I am trying below code to allow cross domain requests.

过滤器

Filter

public class MyCorsFilter implements Filter {

    public MyCorsFilter() { }

    public void init(FilterConfig fConfig) throws ServletException { }

    public void destroy() { }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException  {
      ((HttpServletResponse)response).addHeader("Access-Control-Allow-Origin", "*");
        chain.doFilter(request, response);
    }
}

web.xml

web.xml

<filter>
    <filter-name>MyCorsFilter</filter-name>
    <filter-class>MyCorsFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>MyCorsFilter</filter-name>
    <url-pattern>/api/*</url-pattern>
</filter-mapping>

在添加HTTP基本身份验证之前,上面的代码可以正常工作.

Above code works fine until I add HTTP basic authentication.

当我添加基本身份验证时,出现以下错误:

When I add basic authentication I am getting following error:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

使用开发人员工具检查标头时,我发现以下内容:

When checked headers using developer tools I found following:

请注意,错误是在执行OPTIONS方法时发生的. (我正在使用GET方法)

Please note that the error is while executing OPTIONS method. (I am using GET method)

任何有关如何使用基本HTTP身份验证添加allow CORS的建议都会受到赞赏.

Any suggestion on how to add allow CORS with basic HTTP authentication will be appreciated.

推荐答案

实际上,浏览器会在使用HTTP请求方法"options"进行实际请求之前发出预检请求.因此您必须向该请求发送200 OK,并允许跨域标头,例如

Actually browser makes preflight request before your actuall request with http request method "options" . so you have to send 200 OK to this request and allow cross domain header like

 httpResponse.setHeader("Access-Control-Allow-Origin", "*");
    httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
    httpResponse.setHeader("Access-Control-Max-Age", "3600");
    httpResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization, Content-Type");
    if(httpRequest.getMethod().equals("OPTIONS")){
        httpResponse.setStatus(HttpServletResponse.SC_ACCEPTED);
        return;
    }

您可以在 http://enable-cors-org/

这篇关于球衣跨域请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆