簡體   English   中英

如何以及在何處啟用CORS?

[英]How and where to enable CORS?

我正在嘗試從不在我的域中的api獲取響應。

$.ajax({
                type: "GET",
               url: "http://stage.developmentcheck.org/api/project_monitoring_detail",
               data:{'project_id':'16'},
               error: function (response) {
                        alert('Error: There was a problem processing your request, please refresh the browser and try again');
                },
                success: function (response) {
            console.log(response);
               }
        });

因此錯誤顯示Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://stage.developmentcheck.org/api/project_monitoring_detail?project_id=16. This can be fixed by moving the resource to the same domain or enabling CORS. Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://stage.developmentcheck.org/api/project_monitoring_detail?project_id=16. This can be fixed by moving the resource to the same domain or enabling CORS. 到目前為止,我只使用過html,但是由於我正在使用ajax從api中獲取數據,請啟發我應該在哪里啟用CORS,以及如何啟用? 我嘗試在httpd.conf中添加Header set Access-Control-Allow-Origin "*" ,但沒有用。

http://enable-cors.org/

您確實可以通過apache做。 別忘了在服務器(客戶端)兩端都啟用它。 檢查開發人員工具的“網絡”標簽中的響應標題

服務器端:

要使用Apache向標頭添加CORS授權,只需在服務器配置的<Directory><Location><Files><VirtualHost>部分(通常位於* .conf文件中,例如作為httpd.conf或apache.conf),或在.htaccess文件中:

Header set Access-Control-Allow-Origin "*"

您是否在<Directory><Location><Files><VirtualHost>添加了它? 您不能只將其放在httpd.conf中。 另一個選項是將其放在所需文件夾(例如api文件夾)的.htaccess文件中

jQuery示例:

$.ajax({
    type: "GET",
    url: "http://stage.developmentcheck.org/api/project_monitoring_detail",
    data:{'project_id':'16'},
    crossDomain: true,        
    error: function (response) {
        alert('Error: There was a problem processing your request, please refresh the browser and try again');
    },
    success: function (response) {
        console.log(response);
    }
});

您可以使用PHP來完成。 只需添加標題(“ Access-Control-Allow-Origin:*”); 在您的PHP腳本的開頭。 盡管如果您的PHP設置由於某種原因被某些嚴格的sysadmin弄亂或控制,則無法使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM