jQuery Ajax - POST from Localhost Generates No 'Access-Control-Allow-Origin' header

不羁的心 提交于 2019-12-31 03:57:34

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!