【发布时间】:2015-01-26 05:49:39
【问题描述】:
我通过教程创建了一个基于 php slim 框架的 API,现在我可以注册,使用身份验证登录用户:
URL /register
Method POST
Params name, email, password
/register 调用不需要认证,所以我写了 ajax 来测试 API:
<button id="createPin"></button>
<script>
$(function() {
$('#createPin').click(function(e) {
e.preventDefault();
var dataTest = { "name": "test", "email": "pepe@peperoni.com", "password": "sarasa" }
var urlAjax = "http://www.agroagro.com/test/v1/register";
$.ajax({
type: "POST",
url: urlAjax,
contentType: "application/json",
data: dataTest ,
success: function(data) { alert("ajax worked"); },
error: function(data) {console.log(data); },
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
},
headers: {
'Access-Control-Allow-Origin': '*'
}
});
});
});
</script>
我尝试从 localhost 向 agroagro.com/test/v1/register 运行这个 ajax 调用,但我得到:
XMLHttpRequest cannot load http://www.agroagro.com/test/v1/register. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 404.
是否有任何解决方案可以发出跨域 ajax 请求,因为我计划将此代码用作移动应用程序的前端,所以我需要通过 ajax 跨域发出请求...
(restApi 是按照本教程创建的:http://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-23/)
【问题讨论】:
-
我读过这个,但我不知道如何在我的代码中实现它......我也用 chrom 浏览器试试这个
-
您需要在提供相关 JS 代码的网络服务器上设置 a-c-a-o 标头。如果任何任意 JS 代码都可以设置标头,那么具有跨域限制就没有意义了。 “为什么,是的,我可以和任何我想要的人交谈”。没有。服务器必须包含标题“您可以与 X、Y、Z 交谈”
-
所以我需要在服务器端代码添加:带有访问控制的标头...
-
是的。服务器发送您的 JS 代码,并包含 cors 标头以告诉浏览器允许 js 代码向您指定的任何站点发出请求。 “这里有一些代码。允许向站点 X、Y 和 Z 发出 CORS 请求”。
标签: php jquery ajax rest cross-domain