【问题标题】:API call using ajax not working使用 ajax 的 API 调用不起作用
【发布时间】:2016-03-22 12:53:16
【问题描述】:

我将 CI3 用于我的一个应用程序。 我确实创建了一些使用与应用程序不同的域的 api。

$.ajax({
        url: "http://www.example.com/restapi/index.php/api/user",
        type: "GET",
        data: {"user_id": user_id},
        username: "****",
        password: "****",
        success: function(response){

        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(textStatus, errorThrown);
        },
        xhrFields: { withCredentials: true }
    });

当我使用 jquery ajax 调用这个 api 来获取一些数据时,我得到了错误

NS_ERROR_DOM_BAD_URI: Access to restricted URI denied

所以我知道由于我的应用程序和 api 的子域不同,我无法访问它。

有没有办法允许访问不同子域的api。 我在 API 中使用授权。

我不想调用一些 php 文件,我在其中使用一些 php 函数调用该 API,这没有任何意义。我想直接调用API。

让我知道如何执行此操作并访问 API。

【问题讨论】:

标签: javascript php jquery ajax api


【解决方案1】:

您违反了同源策略 (https://www.w3.org/TR/cors)

子域、不同的端口、不同的协议被认为是不同的域。

<?php
  header("Access-Control-Allow-Credentials: true");
  header("Access-Control-Allow-Methods: GET, OPTIONS"); //Or post
  header("Access-Control-Allow-Origin: http://clientdomain");
?>

这里有更多关于 CI 的详细信息:https://github.com/chriskacerguis/codeigniter-restserver/issues/345

【讨论】:

猜你喜欢
  • 2014-05-01
  • 2018-05-08
  • 2017-02-26
  • 2015-08-07
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多