在 codeigniter 中启用 cors(@chriskacerguis 的 restserver) [英] enabling cors in codeigniter ( restserver by @chriskacerguis )

查看:29
本文介绍了在 codeigniter 中启用 cors(@chriskacerguis 的 restserver)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的客户端应用程序和 api 在本地主机中时,agularJs 控制器中的 http.get 请求工作正常.当 api 移动到服务器时,出现问题.

http.get request in agularJs controller works fine when my client app and api are in localhost. when api is moved to server., issue arised.

客户端使用 angularJs

client side using angularJs

$http.get('http://domain.com/api/spots/2/0').success(function(datas){
console.log(datas);
});

日志给出:跨域请求被阻止:同源策略不允许读取位于 http://domain.com 的远程资源/api/spots/2/0.这可以通过将资源移动到同一个域或启用 CORS 来解决.

log gives: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://domain.com/api/spots/2/0. This can be fixed by moving the resource to the same domain or enabling CORS.

我已将这两行添加到我的控制器构造中

i have added these two lines to my controller construct

header("Access-Control-Allow-Origin: *");

header("Access-Control-Allow-Methods: GET");

还是一样的错误.

推荐答案

尝试将 OPTIONS 添加到允许的方法中.

Try adding OPTIONS to the allowed methods.

header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");

设置标题后,当请求是方法OPTIONS"时立即返回.

and return immediately when the request is method 'OPTIONS' once you have set the headers.

if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
    die();
}

另见这个回答.

Angular 发送一个 符合 W3C CORS 规范的预检请求,它将在实际尝试之前检查允许的正确方法.

Angular sends a W3C CORS spec compliant preflight request that will check for the right allowed methods before actually attempting it.

就我个人而言,我找到了 Mozilla 开发者网络 CORS 页面更容易阅读这件事,以帮助理解 CORS 的流程.

Personally, I find the Mozilla Developer Network CORS page a bit easier to read on the matter to help understand the flow of CORS.

这篇关于在 codeigniter 中启用 cors(@chriskacerguis 的 restserver)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆