I thought I understood CORS, but there is something I do not understand apparently. I have an app that I am trying to run from localhost. This app needs to POST a request to Azure Search. I am trying to upload a search document. In an attempt to do this, I have the following:
var url = 'https://my-app.search.windows.net/indexes/test/docs/index?api-version=2015-02-28';
$.ajax({
url: url,
type: 'POST',
contentType:'application/json',
headers: {
'api-key':'XXXXXX',
'Content-Type':'application/json'
},
beforeSend: function (req) {
req.setRequestHeader('Access-Control-Allow-Origin', '*');
},
data: JSON.stringify({
'@search.action':'upload',
'id': '1',
'name': 'some name'
}),
success: function() { alert('success'); },
error: function() { alert('check the console window.'); }
});
Granted, the url
and api-key
are not the real ones. Still, I can successfully POST this data if I'm using POSTman. Yet, when I try to POST it from my app via jQuery, I get an error in the console window that says:
Failed to load resource: the server responded with a status of 403 (Forbidden)
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:72' is therefore not allowed access. The response had HTTP status code 403.
I have the "Allowed origin type" CORS options for my Azure Search service set to "All". So basically, its wide open. Yet, I still get this CORS error.
How do I POST data to this service from jQuery on localhost?
Azure Search only allows query operations to be performed via CORS, not management or indexing operations (see MSDN for details on Azure Search support for CORS).
The reason for this is that browser-based clients need access to the api-key, and sharing an admin key (which is necessary for index write operations) is inherently insecure. For scenarios where the data in an index is supposed to be publicly available, publicly disclosing a query key is ok, but you should never hand an admin API key to a browser-based client.
来源:https://stackoverflow.com/questions/37127195/jquery-ajax-post-from-localhost-generates-no-access-control-allow-origin-hea