0

Error i see on my console is

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

My Web-app is running at localhost:3000 My server is running at localhost:8081 I am able to hit the services using postman .

Here are the things I already tried :-

One the REST API side I have added CORS filter class :-

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() {
}

}

My web.xml looks like this :-

<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>

On the react application i have added the following headers :-

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

Still i am getting the same issue .

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

When I use no-cors mode in fetch API calls , I am getting 401 error , I guess no-cors mode is not sending Few of the headers .

Other alternative I tries is using @CrossOrigin , but since i am using older version of spring ,I dont support @CrossOrigin , I cant upgrade my version of spring as other old code is breaking onupgradation .

ankit rawat
  • 251
  • 2
  • 4
  • Welcome to Stack Overflow. This question is one that's been asked several times. Please consider searching your question before posting your own. – Grenther Oct 12 '18 at 08:00
  • @Grenther I tried all the approaches from other answers , but none of them seem to work , thats why i posted a new question – ankit rawat Oct 12 '18 at 09:26
  • Please check this answer https://stackoverflow.com/questions/47564671/how-to-specify-response-headers-to-cors/47565689#47565689 – David Pham Oct 12 '18 at 17:56

2 Answers2

0

It seem you misconstrued something here.

The header of CORS should be returned from server and not send from clients (react).

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

Example: You want to send a request from A -> server B.

Browser will send HTTP OPTIONS firstly, to verify if the method is allowed or not, if not allowed it won't send a request.

How browser verify it, it base on the returned header of Server B for HTTP OPTIONS request.

Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: *
Huy Nguyen
  • 1,931
  • 1
  • 11
  • 11
  • and the result? If it's still not working, please update the latest change. – Huy Nguyen Oct 12 '18 at 09:48
  • still having the same issue . – ankit rawat Oct 15 '18 at 07:24
  • Your cors filter is seem not correct. Because you are using Servlet Filter, so please refer to : https://howtodoinjava.com/servlets/java-cors-filter-example/ , you also can configure with spring https://spring.io/blog/2015/06/08/cors-support-in-spring-framework – Huy Nguyen Oct 15 '18 at 07:37
-1

You have to send back to the client from server that this domain is allowed or not

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
    }

}

Define that in xml as below :

<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>
Ishant Gaurav
  • 1,183
  • 2
  • 13
  • 32