-1

I have a situation I can't really understand. Two computers, in one I'm using brackets for my Web development, in the other (Linux) I'm running Tomcat (7). Both are within the same LAN (and hence same address range). I'm getting the error shown in the title and hence I'm completely stuck. Tried the following code with no success:

var req = { url: l_url, method:"POST", headers: { 
                    'Content-Type': 'application/x-www-form-urlencoded' ,
    //                'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Origin': 'http://127.0.0.1',
                    'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
                    'Access-Control-Allow-Headers': 'Content-Type, application/x-www-form-urlencoded'
                    }, data: l_params } ;

$http(req).
            success(function(data, status, headers, config) {
                console.log("DB_Services - Success; data is: " + JSON.stringify(data)) ;
                 l_deferred.resolve(data);
            }).
            error(function(data, status, headers, config) {
                console.log("DB_Services - Error: " + data) ;
                 l_deferred.reject(status);
            });
             return l_deferred.promise;

The error (Chrome's console) reads: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:58275' is therefore not allowed access.

My search brought me to the conclusion (not sure it is correct) that the Tomcat is rejecting the request, even though I included the above shown heading details.

I also found that it is possible to tell Tomcat to allow the request, but don't know how and where to configure that.

So, my questions are:

1) Is my http request properly phrased?

2) How do I make Tomcat to allow this request?

Thanks in advance for any suggestion.

FDavidov
  • 3,505
  • 6
  • 23
  • 59
  • 1
    Possible duplicate of [Ways to circumvent the same-origin policy](http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy) – Marged Jan 23 '16 at 10:26
  • It does not make any sense to set the cors headers on the requestors side – Marged Jan 23 '16 at 10:27
  • Having a look at your subsequent questions I come to the conclusion that you should do some research in cors. Have a look at http://enable-cors.org – Marged Jan 23 '16 at 11:06

2 Answers2

1

You could try adding a filter class to your java code in the server side, sample code

public class CorsFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    response.addHeader("Access-Control-Allow-Origin", "*");
    if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
        //Add CORS "pre-flight" request
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
         response.addHeader("Access-Control-Allow-Headers", "Authentication-token");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
        response.addHeader("Access-Control-Max-Age", "3600");
    }
    filterChain.doFilter(request, response);
}

}

add it to web.xml

<filter>
    <filter-name>cors</filter-name>
    <filter-class>location.of.filter.class</filter-class>
</filter>
<filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

and in in your angular js app config try adding

app.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);

this had solved my problem, hope it will help you too.

  • Thanks @JovinThariyath for your response. I have one question though: The first piece of code suggests that it is not TOMCAT rejecting the request but the SERVLET itself. Am I understanding correctly? – FDavidov Jan 23 '16 at 10:39
  • Yup I too think so, that's why adding filter resolves the problem from the server side. – Jovin Thariyath Jan 23 '16 at 11:06
  • OK. Will try it. Question: Within the JAVA I should add the class `CorsFilter` as you provided above. Is just "adding" it to the WAR enough or I need to do something more? – FDavidov Jan 23 '16 at 11:28
  • Thanks. Will try and let you know. – FDavidov Jan 23 '16 at 12:23
  • OK... I'm using Eclipse LUNA for the servlets. Added a new class (CorsFilter) and copied-pasted the code you posted. Eclipse does not recognize OncePerRequestFilter nor it has any proposal to use. Where is this class coming from? – FDavidov Jan 23 '16 at 12:37
  • it is part of spring web, since you are using standard servlet try solution given in this link http://amodernstory.com/2014/12/27/using-cors-headers-with-java-example/ – Jovin Thariyath Jan 23 '16 at 12:46
  • YES!!!!!!!!!!!! I just needed to copy-paste the filter definition included in the link you provided and... voila (or however it is written). It work perfectly!!! Thank you Sir!!!! – FDavidov Jan 23 '16 at 13:24
0

You are running into what's known as the Same-Origin Policy. One of the core motives behind this policy is to prevent scripts that you didn't write (and thus are untrusted) from running on your page (and possibly taking data from it). Scripts that attempt to do that maliciously are doing what is known as Cross-Site Scripting.

To not run afoul of the Same-Origin Policy, your site must only ask for scripts from:

  1. A site with the same protocol as your site
  2. A site with the same hostname as your site
  3. A site with the same port as your site

You'll notice this basically means only your site.

One newer method of getting around this restriction is to use Cross-Origin Resource Sharing (CORS). To do this you must have control of the code/servers for all the scripts you would like to run.

There is already good SO question/answer to get you started: Ways to circumvent the same-origin policy

Community
  • 1
  • 1
Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128
  • Thank you @MatthewHerbst for your response. I do understand the reason for CORS. My point is that I'm running within the same LAN, same address range, and hence (in theory at least) same domain. Moreover, I defined (hosts file) aliases for both computers such as: `MyPC.MyDomain.com` and `MyServer.MyDomain.com`. I think this has to do with the fact that **Brackets** uses the localhost alias as source (that is why we see "127.0.0.1:xxx' in the origin). Last, I tried the `'Origin':'http://MyPC.MyDomain.com'` header and got `Refused to set unsafe header "Origin"`. – FDavidov Jan 23 '16 at 10:51
  • Different subdomains = different domains as far as SOP is concerned. – Matthew Herbst Jan 23 '16 at 11:00
  • Cors is even necessary when only the port differs: host:81 is not allowed to talk to host:80 – Marged Jan 23 '16 at 11:04