简体   繁体   English

使用PHP作为服务器和jQuery作为客户端来创建一个宁静的API

[英]Creating a restful API using PHP as server and jQuery as client

I'm trying to create a Javascript client API service which calls the API of my site. 我正在尝试创建一个Javascript客户端API服务,该服务调用我网站的API。 This will be cross domain and i'm aware of the problems this causes. 这将是跨域的,我知道这会导致问题。 However, I need the user to send through some user credentials (whether that be their username and password encoded obviously or an API key + secret) so that I can return user specific details. 但是,我需要用户发送一些用户凭据(无论是用户名和密码是否经过明显编码,还是API密钥+机密),以便我可以返回用户特定的详细信息。

I initially looked at using the jsonp datatype however this doesnt allow you to set any custom headers so ruled this out. 我最初看过使用jsonp数据类型,但是这不允许您设置任何自定义标头,因此将其排除在外。

I've been searching the web for a while and been unable to find a secure way of doing this cross domain, has anyone had any success with this and can give me some advice? 我已经在网上搜索了一段时间,却无法找到一种安全的方式来进行跨域访问,有人在此方面取得了成功,可以给我一些建议吗?

UPDATE: 更新:

I've tried this following code as suggested by lu1s, however I get an alert of 'boo' as stated n the error function.. 我已经按照lu1s的建议尝试了以下代码,但是在错误函数中显示了“ boo”的警报。

$.ajax({
    url: 'http://www.dotsandboxes.co.cc/__tests/cors.php',
    type: 'GET',
    dataType: 'json',
    success: function() { alert('hello!'); },
    error: function() { alert('boo!'); },
    beforeSend: function (xhr) {
        xhr.setRequestHeader('securityCode', 'Foo');
        xhr.setRequestHeader('passkey', 'Bar');
    }
});

Thanks 谢谢

You can. 您可以。 Try adding the Allow-Access-Control-Origin: * to your HTTP response headers, as well as the correct content-type. 尝试将Allow-Access-Control-Origin: *和正确的内容类型添加到HTTP响应标头中。

Try with a simple PHP script like this: 尝试使用以下简单的PHP脚本:

<?php
    header('Access-Control-Allow-Origin: *');
    header('Content-type: text/json');
    echo json_encode(array('success'=>true,'data'=>'foobar'));
?>

Check this site to read more info about cross-origin: http://enable-cors.org/ 检查此站点以了解有关跨域的更多信息: http : //enable-cors.org/

About the authentication, it's NOT recommended to send usernames or passwords, even if they're encrypted. 关于身份验证,即使已加密用户名或密码,也不建议发送用户名或密码。 As you stated, it's better to pass a token in the URL. 如您所述,最好在URL中传递令牌。 Best if following standards like http://oauth.net/2/ . 最好遵循http://oauth.net/2/之类的标准。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM