2017-05-16 19 views
0

我正在用Django + Phonegap構建應用程序。當我嘗試使用這個函數來發送一個Ajax請求:即使存在請求的資源,也不存在'Access-Control-Allow-Origin'標頭

<script> 
 
     $.ajax({ 
 
     url: "http://192.168.0.101/commerce/product/" + localStorage.getItem("toView"), 
 
     type: "GET", 
 
     data: {}, 
 

 
     success: function (json) { 
 

 
      console.log(json); 
 

 
     } 
 

 
     }); 
 
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

我得到在Chrome控制檯的錯誤說:

的XMLHttpRequest無法加載http://192.168.0.101/commerce/product/2。 從'http://192.168.0.101/commerce/product/2'重定向到 'http://192.168.0.101/commerce/product/2/'已被CORS 阻止策略:否 請求的資源上存在'Access-Control-Allow-Origin'標頭。原因'http://192.168.0.101:3000'因此是 不允許訪問。

問題在於,我包含了請求的標題。當我在chrome中打開給定的URL並查看服務器響應時,我得到了這個結果。

HTTP/1.0 200 OK 
Date: Tue, 16 May 2017 09:42:29 GMT 
Server: WSGIServer/0.2 CPython/3.4.3 
Content-Type: application/json 
Access-Control-Allow-Origin: * 
X-Frame-Options: SAMEORIGIN 
Access-Control-Allow-Methods: OPTIONS,GET,PUT,POST,DELETE 
Access-Control-Allow-Headers: X-Requested-With, Content-Type 
Content-Length: 89 

我還包括views.py我的服務器代碼我。

def product(request, prod_id): 

    #### SOME CODE 

    response = JsonResponse(response_data) 
    response['Access-Control-Allow-Origin'] = '*' 
    response['Access-Control-Allow-Methods'] = 'OPTIONS,GET,PUT,POST,DELETE' 
    response['Access-Control-Allow-Headers'] = 'X-Requested-With, Content-Type' 

    return response 

爲什麼我得到這個錯誤?請幫忙。謝謝。

回答

1

你應該在ajax要求在URL的末尾添加斜線:

url: "http://192.168.0.101/commerce/product/" + localStorage.getItem("toView") + '/', 

的Django需要一個斜線附加到的URL。

+0

是的,這樣做。爲什麼? – TheRandomGuy

+0

這是django接受的正確網址。你可以在錯誤日誌中看到它抱怨缺少的斜線 – doru

相關問題