1

I am using backbonejs in my sample appliction. previously, I was hosting this on nodejs but now want to run it on tomcat but this change is giving me an error on the client browser. I search and found that to solve this issue crossdomain (https://stackoverflow.com/a/33820700/5086633) has to be set to true. Not sure how and were should I handle this. Any help in this regard is highly appreciated.

   XMLHttpRequest cannot load http://localhost:8080/backbonejs/testpost. 
    Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.
 Origin 'null' is therefore not allowed access. The response 
had HTTP status code 403.

Using ajaxPrefilter, model and collection as below.

$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
      options.url = 'http://localhost:8080/backbonejs' + options.url;
    });
var Banks = Backbone.Collection.extend({
      url: '/testpost'
    });

    var Bank = Backbone.Model.extend({
      urlRoot: '/testpost'
    });
Community
  • 1
  • 1
yeppe
  • 679
  • 1
  • 11
  • 43
  • 2
    On the server side, you have to allow the cross domain. Take a look at that : http://stackoverflow.com/questions/7067966/how-to-allow-cors-in-express-node-js – krakig Apr 13 '16 at 09:53
  • 2
    Ah true, I was thinking that your back-end was node.js. I am not experienced in tomcat, but this should help you : http://enable-cors.org/server_tomcat.html – krakig Apr 13 '16 at 09:58

3 Answers3

3

In express.js:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

In native NodeJS server:

res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
József Cserkó
  • 299
  • 2
  • 9
1

I added this in Web.xml it worked.

 <filter>
      <filter-name>CorsFilter</filter-name>
      <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    </filter>
    <filter-mapping>
      <filter-name>CorsFilter</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>
yeppe
  • 679
  • 1
  • 11
  • 43
1

Can also be achieved using this... This post was handy How to setup Access-Control-Allow-Origin filter problematically in Spring Security 3.2 no need to do that in tomcat server. Also, I did not use the AddFilterBefore here. below code was enough to do resolve the issue.

    rootContext.setServletContext(container); 

             FilterRegistration.Dynamic corsFilter = 
container.addFilter("corsFilter", CORSFilter.class);

 corsFilter.addMappingForUrlPatterns(null, false, "/*");
Community
  • 1
  • 1
yeppe
  • 679
  • 1
  • 11
  • 43