使用 ajax 的 API 调用不起作用

API call using ajax not working

本文关键字:调用 不起作用 API ajax 使用      更新时间:2023-09-26

我正在将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 }
    });

当我调用此 api 使用 jquery ajax 获取一些数据时,出现错误

NS_ERROR_DOM_BAD_URI: Access to restricted URI denied

所以我了解到,由于我的应用程序和 API 的子域不同,我无法访问它。

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

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

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

您违反了同源策略 (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