7

I am trying to send data to servlet using angular http post,

var httpPostData = function (postparameters,postData){

     var headers = {
                'Access-Control-Allow-Origin' : '*',
                'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS',
                'Accept': 'application/json'
            };
  return $http ({

    method  : 'POST',
    url     : 'http://localhost:8080/json/jasoncontroller',
    params  : postparameters,
    headers: headers,
    data    : postData
   }).success (function (responseData){
         return responseData.data;
   })
}

But i am keep on getting error that No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

I did have set following headers on my servlet

    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
    response.addHeader("Access-Control-Max-Age", "3600");
    response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

if i remove data from http post it works fine, but no luck with data.

enter image description here

Nomad
  • 1,019
  • 4
  • 16
  • 30
  • check status and response headers of OPTIONS request made. Those access control headers must be in that preflight request – charlietfl Sep 26 '15 at 12:16
  • 1
    I've had the same issue and I solved using `response.setHeader("Access-Control-Allow-Origin", "*");` instead of `response.addHeader("Access-Control-Allow-Origin", "*");`. If you use `addHeader` method it allows many values to the same header according to the API. See [javadoc](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletResponse.html#addHeader-java.lang.String-java.lang.String-). – Ruben O. Chiavone Sep 26 '15 at 12:22
  • @charlietfl added image of network response header. – Nomad Sep 26 '15 at 12:26
  • @RubenO.Chiavone tried that too, didnt work – Nomad Sep 26 '15 at 12:26
  • server not setting the access-control headers on OPTIONS request. That is the important one....POST won't get made if it isn't valid – charlietfl Sep 26 '15 at 12:29
  • Take a look at this: http://enable-cors.org/server.html and http://enable-cors.org/server_tomcat.html. Tomcat enabled CORS starting from version 7.0.41. What version are you using? – Ruben O. Chiavone Sep 26 '15 at 12:31
  • how can i set access-control headers on OPTIONS request, cause response.setHeader("Access-Control-Allow-Origin", "*"); clearly not working.. – Nomad Sep 26 '15 at 12:39

1 Answers1

0

Actually what happens is in some frameworks two calls are made,

  • OPTIONS which checks what methods are available,
  • And then there is the actual call.

OPTIONS require just empty answer 200 OK

if(request.methord == 'OPTIONS'){
  res.send(200);
  } else {
   next();
  }

You can also install this chrome extension to enable cors, that is the easy way out !

Rohan Goel
  • 31
  • 6