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

I am trying to send data to a 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 keep getting the error that the No header 'Access-Control-Allow-Origin' is present on the requested resource. Therefore, the initial value of "null" is not allowed.

I set the 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 delete the data from the http post, it works fine but fails with the data.

enter image description here

+7
java javascript jquery angularjs servlets
source share
1 answer

In fact, what happens, in some frameworks, two calls are made,

  • OPTIONS that check which methods are available
  • And then there is the actual call.

OPTIONS require only an empty answer 200 OK

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

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

0
source

All Articles