我正在将 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 )
子域、不同端口、不同协议(protocol)被视为不同的域。
<?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
关于javascript - 使用 ajax 的 API 调用不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36154931/