duanqin4238
2014-11-27 15:17
浏览 313
已采纳

发送ajax POST请求到restful api

I create an php slim framework based API by tutorial an now i'm able to register,login user with autentification:

URL     /register
Method  POST
Params  name, email, password

/register call dont need autentification so I write ajax to test 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>

I try to run this ajax call from localhost to agroagro.com/test/v1/register but I get:

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.

Is there any solution to make cross-domain ajax request becouse I have a plan to use this code as frontend of an mobile app, so I need to make requests via ajax cross-domain...

(restApi was created by following this tutorial:http://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-23/)

图片转代码服务由CSDN问答提供 功能建议

我通过教程创建一个基于php的框架API,现在我可以注册,登录用户使用autentification:

  URL / register 
Method POST 
Params name,email,password 
   
 
 

/ register call不需要autentification 所以我写ajax来测试API:

 &lt; button id =“createPin”&gt;&lt; / button&gt; 
&lt; script&gt; 
 $(function(){  
 $('#createPin')。click(function(e){
 e.preventDefault(); 
 
 
 var dataTest = {“name”:“test”,“email”:“pepe @  peperoni.com“,”“密码”:“sarasa”} 
var urlAjax =“http://www.agroagro.com/test/v1/register";
nn.ajax({
type:"POST”  ,
url:urlAjax,
contentType:“application / json”,
data:dataTest,
success:function(data){alert(“ajax working”);},
error:function(data){console.log(  data);},
dataType:'json',
beforeSend:function(xhr){
 xhr.setRequestHeader(“Access-Control-Allow-Origin”,“*”); 
},
标题 s:{
'Access-Control-Allow-Origin':'*'
} 
}); 
 
 
});  
}); 
&lt; / script&gt; 
   
 
 

我尝试从localhost运行此ajax调用到agroagro.com/test/v1/register但我得到了 :

  XMLHttpRequest无法加载http://www.agroagro.com/test/v1/register。 请求的资源上不存在“Access-Control-Allow-Origin”标头。 因此不允许原点'null'访问。 响应有HTTP状态代码404. 
   
 
 

是否有任何解决方案可以使跨域ajax请求因为我有计划使用此代码作为移动设备的前端 app,所以我需要通过ajax跨域提出请求...

(restApi是通过以下教程创建的: http:// www .androidhive.info / 2014/01 /如何对创建静止-API换机器人-APP-使用-PHP-超薄和MySQL的天-23 /

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doumo0206 2014-11-27 16:09
    已采纳

    You need to set the correct header responses.

    In my case, I have a set of default header that I always set when I receive a call to my api controller. This is set in my _construct

    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
    header("Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization");
    

    There are some really helpful guide that will help you understand how CORS works and why you need it.

    Cross-origin resource sharing

    Cross-domain Ajax with Cross-Origin Resource Sharing

    EDIT:

    First you need to allow access to all origins by using Access-Control-Allow-Origin : *, you are doing this now so you will see a different error from the original one posted. I had a similar issue when using phoneGap and Ionic and it was solved by added the content-type header to my ajax call. This post helped me XMLHttpRequest cannot load.

    I am using Codeigniter for my API so I don't know how much of this will help but it's very generic so should point you in the right direction.

    I have a controller called API which is used to fetch data from a database and return JSON.

    class Api extends CI_Controller {
        ....
        ....
    }
    

    In this class I have a __construct function. A __construct is always run when the class in called so you don't need to call it yourself. Within the __construct set the headers CORS headers.

    public function __construct()
    {
        parent::__construct();
    
        // Set access header
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
        header("Access-Control-Allow-Headers: Origin, HTTP_X_REQUESTED_WITH, Content-Type, Accept, Authorization");
    
        ....
        ....
    }
    

    I hope this helps

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题