2017-08-11 147 views
1

我有一個ARC由客戶端設置,一切似乎在ARC和後端是工作好了,但我看不出什麼,我在jQuery的高級REST客戶端的jQuery請求

做錯了

這裏的在ARC測試

enter image description here

這裏是我的jQuery代碼

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width"> 
    <title>JS Bin</title> 
    <script 
    src="https://code.jquery.com/jquery-2.2.4.min.js" 
    integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" 
    crossorigin="anonymous"></script> 
    <script> 
    let urlBase = 'http://54.210.29.209'; 
    let urlEnterEmail = '/api/v1/users/checkEmail'; 

    $(document).ready(function() { 

     $.ajax(
     { 
      method: "POST", 
      crossDomain: true, 
      url: urlBase + urlEnterEmail, 
      xhrFields: {withCredentials: true}, 
      headers: { 
      "Access-Control-Request-Headers": "x-requested-with", 
      "Content-Type": "application/json", 
      "Platform": "web", 
      "Build": 2 
      }, 
      contentType: "application/json; charset=utf-8", 
      dataType: 'json', 
      data: {"email": "[email protected]"} 
     } 
    ) 
     .done(function (response) { 
     console.log('done!'); 
     console.log(response); 
     }) 
     .fail(function (xhr, status) { 
     console.log('fail!!!'); 
     //console.log(xhr); 
     console.log(status); 
     }); 

    }); 
    </script> 
</head> 
<body> 

</body> 
</html> 

最後,錯誤

enter image description here

我讀了一點關於CORS,但它不工作。我發現的資源如下,但我不知道我是否是有問題或後端代碼的人。

How to get a cross-origin resource sharing (CORS) post request working

https://www.html5rocks.com/en/tutorials/cors/

+0

而你沒有收到任何錯誤,也沒有迴應? – adeneo

+0

嘗試串化您的數據 - 數據:JSON.stringify({「email」:「[email protected]」}) – Shane

+0

@Shane noup ...不使用stringify :( – pctroll

回答

1

[此示例使用ASPNET網絡API,C#作爲後端] 您的問題似乎涉及到了API,而不是你的JavaScript調用本身, 看看這個,這是一個跨源電話:

$.ajax({ 
     type: 'POST', 
     url: CTHelper.ApiUrl() + '/token', 
     data: { grant_type: 'password', username: $scope.UserName, password: $scope.Password }, 
     success: function (result) { 
      alert('OK'); 
     }, 
     error: function (result) { 
      alert('Error'); 
     } 
    }); 

但我的API(後端)允許CORS,這是文件Startup.Auth.cs的一部分

public void ConfigureAuth(IAppBuilder app) 
    { 
     ... 
     app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); 
     ... 
    } 

Microsoft.Owin.Cors可以作爲nuget下載。

1

你的問題在那裏明確說明。由於缺少來自服務器的Access-Control-Allow-Origin(跨站點請求)標頭,Web瀏覽器限制您訪問後端。

如果你的後臺運行PHP,在腳本的第一行用這已經足夠了:

<?php 
    header("Access-Control-Allow-Origin: *"); 
    // The rest of your backend script here 
    // ... 

這askerisk(*)基本上會說「接受來自每個源的請求」。當然,如果網頁從其加載(基本上它的原點相同),則可以使用後端的相同地址。因此,如果這些文件上傳到你的服務器腳本的一面,這應該工作太:

<?php 
    header("Access-Control-Allow-Origin: http://54.210.29.209"); 

我真的不知道,如果使用http://localhost會的工作,可能不會,但它是值得一試的。