简体   繁体   中英

Angular http post request - No 'Access-Control-Allow-Origin' header is present on the requested resource

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.

在此输入图像描述

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 !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM