简体   繁体   中英

AngularJS / CORS OPTIONS request and performance

I'm making a cross-domain CORS POST request in AngularJS as follows:

var url = 'https://api.myapp.tld';
var userObj = { username:'foo', password: 'bar' };

$http.post(url,userObj).success(function(data){
  // do success stuff
}).error(function(data){
  // do FAIL stuff
});

As per the standard Angular will 'preflight' this with an OPTIONS request. My server returns a 204 header with the requisite access-control headers to allow the client continue. So far so good.

However this happens before every POST request, unless they occur in very quick succession in which case I can get a few in a row (so it seems there's some sort of timeout maybe). My app is a mobile web app so I worry that these extra options requests could negatively impact performance over 3G (or Edge) networks.

My question is: Can the server's response to the options request indicate to the client that it can store the rules for a longer period?

Angular doesn't need this configuration--your server needs to add the proper cache headers on the OPTIONS request. See: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Max-Age

You can also avoid the preflight request altogether if you are willing to alter your API a bit so that common endpoints are considered "simple requests".

I've got a post covering all the restrictions and how to get around them called Two Strategies for Crossing Origins with Performance in Mind .

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