2017-08-11 150 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会的工作,可能不会,但它是值得一试的。