I am trying to build a small web app in Dart. The app calls the EasyPost web service, as illustrated with this curl call:
$ curl -X POST https://[email protected]/v2/trackers
-d 'tracker[tracking_code]=EZ1000000001'
-d 'tracker[carrier]=FEDEX'
Here is the Dart code that I attempted to match this request:
// Configuration parameters
var url = "https://[email protected]/v2/trackers";
var data = {
'tracker[tracking_code]': '$packageNo',
'tracker[carrier]': 'FEDEX'
};
// Make the request
var request = new HttpRequest();
request
..open("POST", url, async: true)
..withCredentials = true
..onLoadEnd.listen((_) => print(request.responseText))
..send(data.toString());
When I run this in WebStorm the code fails when making the request with a CORS error:
POST https://api.easypost.com/v2/trackers 401 (Unauthorized)
XMLHttpRequest cannot load https://api.easypost.com/v2/trackers.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:63342' is therefore not allowed
access. The response had HTTP status code 401.
Isn't that supposed to be handled automatically? Or do I need to add those headers to the request myself?
The headers need to be added by the server, otherwise the client won't make the request. With a
POST
request the browser makes a preflight request to check the CORS headers. If they are not added by the server, the browser just doesn't make the actualPOST
request.If the server doesn't add these headers it's probably not intended to be used this way.
There are some possible workarounds: http://usamadar.com/2012/06/24/getting-around-browsers-same-origin-policy-sop-with-proxies-script-injection-jsonp-and-cors/