doty58493 2015-02-09 01:47
浏览 66

通过jQuery 401调用REST服务

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() . '}}';
      }
    }

    [...]
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 如何在scanpy上做差异基因和通路富集?
    • ¥20 关于#硬件工程#的问题,请各位专家解答!
    • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
    • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
    • ¥30 截图中的mathematics程序转换成matlab
    • ¥15 动力学代码报错,维度不匹配
    • ¥15 Power query添加列问题
    • ¥50 Kubernetes&Fission&Eleasticsearch
    • ¥15 報錯:Person is not mapped,如何解決?
    • ¥15 c++头文件不能识别CDialog