从ReactJS进入REST服务时,出现CORS问题

时间:2018-10-12 07:40:31

标签: java reactjs spring-boot cors

我在控制台上看到的错误是

对预检请求的响应未通过访问控制检查:所请求的资源上不存在“ Access-Control-Allow-Origin”标头。因此,不允许访问来源“ http://localhost:3000”。响应的HTTP状态码为401。如果不透明的响应满足您的需求,请将请求的模式设置为“ no-cors”,以在禁用CORS的情况下获取资源。

我的Web应用程序正在本地主机上运行:3000 我的服务器在本地主机上运行:8081 我可以使用邮递员服务。

这是我已经尝试过的东西:-

我在REST API方面添加了CORS过滤器类:-

public class CORSFilter implements Filter {
public static final String ACCESS_CONTROL_ALLOW_ORIGIN_NAME = "Access-
Control-Allow-Origin";
public static final String DEFAULT_ACCESS_CONTROL_ALLOW_ORIGIN_VALUE = "*";

public static final String ACCESS_CONTROL_ALLOW_METHDOS_NAME = "Access-
Control-Allow-Methods";
public static final String DEFAULT_ACCESS_CONTROL_ALLOW_METHDOS_VALUE = "*";

public static final String ACCESS_CONTROL_MAX_AGE_NAME = "Access-Control-Max-
Age";
public static final String DEFAULT_ACCESS_CONTROL_MAX_AGE_VALUE = "3600";

public static final String ACCESS_CONTROL_ALLOW_HEADERS_NAME = "Access-
Control-Allow-Headers";
public static final String DEFAULT_ACCESS_CONTROL_ALLOW_HEADERS_VALUE = "*";

private String accessControlAllowOrigin = 
DEFAULT_ACCESS_CONTROL_ALLOW_ORIGIN_VALUE;
private String accessControlAllowMethods = 
DEFAULT_ACCESS_CONTROL_ALLOW_METHDOS_VALUE;
private String accessControlAllowMaxAge = 
DEFAULT_ACCESS_CONTROL_MAX_AGE_VALUE;
private String accessControlAllowHeaders = D 
DEFAULT_ACCESS_CONTROL_ALLOW_HEADERS_VALUE;


 private Map<String,String> initConfig(){
    Map<String, String> result = new HashMap<String,String>();

    result.put(ACCESS_CONTROL_ALLOW_ORIGIN_NAME,"accessControlAllowOrigin");

result.put(ACCESS_CONTROL_ALLOW_METHDOS_NAME,"accessControlAllowMethods");
    result.put(ACCESS_CONTROL_MAX_AGE_NAME,"accessControlAllowMaxAge");

result.put(ACCESS_CONTROL_ALLOW_HEADERS_NAME,"accessControlAllowHeaders");

    return result;
}

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    String initParameterValue;
    Map<String, String> stringStringMap = initConfig();

    for (Map.Entry<String, String> stringStringEntry : 
stringStringMap.entrySet()) {
        initParameterValue = 
filterConfig.getInitParameter(stringStringEntry.getKey());


        if(initParameterValue!=null){
            try {
                getClass().getDeclaredField(stringStringEntry.getValue()).set(this, initParameterValue);
            } catch(Exception ex) { }
        }
    }
}

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse 
servletResponse, FilterChain filterChain) throws IOException, 
ServletException {
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    response.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN_NAME, 
accessControlAllowOrigin);
    response.setHeader(ACCESS_CONTROL_ALLOW_METHDOS_NAME, 
accessControlAllowMethods);
    response.setHeader(ACCESS_CONTROL_MAX_AGE_NAME, 
accessControlAllowMaxAge);
    response.setHeader(ACCESS_CONTROL_ALLOW_HEADERS_NAME, 
accessControlAllowHeaders);

    filterChain.doFilter(servletRequest, servletResponse);
}

@Override
public void destroy() {
}

}

我的web.xml看起来像这样:-

<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">

<filter>
    <filter-name>CORSFilter</filter-name>
    <filter-
class>com.barclaycardus.svc.agentprofile.config.CORSFilter</filter-class>
</filter>


<filter-mapping>
    <filter-name>CORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

在react应用程序上,我添加了以下标头:-

 headers1.append('Access-Control-Allow-Origin', '*');
 headers1.append('Access-Control-Allow-Credentials', 'true');

仍然我遇到同样的问题。

var request = new Request(url, {
method: 'GET',
headers:headers1,
cache:'no-cache'
// mode:'no-cors'
});

当我在获取API调用中使用no-cors模式时,出现401错误,我猜no-cors模式未发送少量标头。

我尝试的其他替代方法是使用@CrossOrigin,但是由于我使用的是Spring的旧版本,因此我不支持@CrossOrigin,因此我无法升级spring版本,因为其他旧代码破坏了升级。

2 个答案:

答案 0 :(得分:1)

似乎您在这里误解了一些东西。

应该从服务器返回CORS的标头,而不是从客户端发送(反应)。

Access-Control-Allow-Origin
Access-Control-Allow-Credentials

示例: 您要从A->服务器B发送请求。

浏览器将首先发送HTTP OPTIONS,以验证是否允许该方法,如果不允许,它将不会发送请求。

浏览器如何验证它,它基于服务器B返回的HTTP OPTIONS请求标头。

Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: *

答案 1 :(得分:0)

您必须从服务器允许该域允许或不允许发送回客户端

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class CORSFilter
 */
// Enable it for Servlet 3.x implementations
/* @ WebFilter(asyncSupported = true, urlPatterns = { "/*" }) */
public class CORSFilter implements Filter {

    /**
     * Default constructor.
     */
    public CORSFilter() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        System.out.println("CORSFilter HTTP Request: " + request.getMethod());

        // Authorize (allow) all domains to consume the content
        ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Origin", "*");
        ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Methods","GET, OPTIONS, HEAD, PUT, POST");

        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        // For HTTP OPTIONS verb/method reply with ACCEPTED status code -- per CORS handshake
        if (request.getMethod().equals("OPTIONS")) {
            resp.setStatus(HttpServletResponse.SC_ACCEPTED);
            return;
        }

        // pass the request along the filter chain
        chain.doFilter(request, servletResponse);
    }

    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

}

在xml中定义如下:

<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>com.ishant.examples.cors.CORSFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>