通过jQuery 401调用REST服务

我目前正在尝试从使用PHP / Slim创建的REST服务中检索数据。 该服务从数据库中检索数据很好,但是当我尝试通过AJAX调用获取此数据时,我遇到了401 Unauthorized Error。 </ p>

最初控制台说它是由于没有 Access-Control-Allow-Origin </ code>参数集,但是这是通过将参数添加到 web.config </ code>(IIS) - 现在我刚刚在Chrome控制台中登录了 GET http:// localhost:8081 / api / v1 / users 401(未经授权)</ code>。< / p>

该调用旨在托管在不同的服务器上,因此,为了进行测试,我已使用上的RESTful服务将该站点置于端口:8082 </ code>上: 8081 </ code>。</ p>

我的AJAX调用编写如下(我还尝试过 jsonp </ code>但由于URL重写?callback =。 .. </ code>抛出404错误。)</ p>

  $ .ajax({
type:'get',
url:'http:// localhost: 8081 / api / v1 / users',
dataType:'json',
success:function(data){
console.log(data);
}
});
</ code> < / pre>

我的RESTful服务编写如下:</ p>

  header('Content-Type:application / json'); 

/ /加载Slim框架
需要'Slim / Slim.php';
\ Slim \ Slim :: registerAutoloader();

//创建一个新的Slim对象
$ app = new Slim \ Slim();

//定义RESTful动作
$ app-&gt; get('/ users',function(){get(“SELECT * FROM users”); }
;

函数get($ sql){
try {
$ db = getConnection();
$ stmt = $ db-&gt; query($ sql);
$ results = $ stmt - &gt; fetchAll(PDO :: FETCH_ASSOC);
echo'{'。 json_encode($ results)。 '}';
}
catch(PDOException $ e){
echo'{“错误”:{“Text”:'。 $ e-&gt; getMessage()。 '}}';
}
}

[...]
</ code> </ pre>
</ div>

展开原文

原文

I am currently attempting to retrieve data from a REST service I created with PHP/Slim. The service retrieves data from the database fine, however when I try to get this data through an AJAX call I am faced with a 401 Unauthorized Error.

Originally console was saying it was due to not having an Access-Control-Allow-Origin parameter set, but this was fixed by adding the parameter into web.config (IIS) - Now I am just left with GET http://localhost:8081/api/v1/users 401 (Unauthorized) logged in the Chrome console.

The call is intended to be hosted on a different server, so for testing I have put the site onto port :8082 with the RESTful service on :8081.

My AJAX call is written as follows (I have also tried jsonp but due to URL Rewrite the ?callback=... throws a 404 error).

$.ajax({
  type: 'get',
  url: 'http://localhost:8081/api/v1/users',
  dataType: 'json',
  success: function(data) {
    console.log(data);
  }
});

My RESTful service is written as follows:

    header('Content-Type: application/json');

    // Load the Slim framework
    require 'Slim/Slim.php';
    \Slim\Slim::registerAutoloader();

    // Create a new Slim object
    $app = new Slim\Slim();

    // Define RESTful actions
    $app->get('/users', function() { get("SELECT * FROM users"); });

    function get($sql) {
      try {
        $db = getConnection();
        $stmt = $db->query($sql);
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo '{' . json_encode($results) . '}';
      }
      catch (PDOException $e) {
        echo '{"Error": {"Text": ' . $e->getMessage() . '}}';
      }
    }

    [...]

duanliusong6395
duanliusong6395 您可以尝试直接使用浏览器访问该服务吗?
5 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问