我在localhost(xampp)/ codeigniter上有api,我试图通过角度4访问它,浏览器一直在控制台中显示此错误 . api在邮递员工作得很好 .
[火狐]:
跨源请求已阻止:同源策略不允许在http://lvh.me/ci-abc/api/get_alltasks上读取远程资源 . (原因:缺少CORS Headers 'Access-Control-Allow-Origin') .
[铬]:
无法加载http://lvh.me/ci-abc/api/get_alltasks:请求的资源上没有“Access-Control-Allow-Origin”标头 . 因此不允许来源'http:// localhost:4200'访问 .
我已经尝试将API URL更改为localhost和127.0.0.1但是没有用 . 我是一名初学者,如果我错过了什么,请原谅我 .
Angular 4中的服务功能
gettasks()
{
return this.http.get('http://lvh.me/ci-abc/api/get_alltasks')
.map(res=>res.json());
}
codeigniter中的API函数
function get_alltasks_get()
{
{
$result = $this->todo_model->get_alltasks();
if ($result) {
$this->response($result, 200);
} else {
$this->response("No record found", 404);
}
}
}
2 回答
CORS on PHP
如果您无权配置Apache,则仍可以从PHP脚本发送标头 . 这是在PHP脚本中添加以下内容的情况:
它's not Angular problem, the problem caused because you'与您的服务器不在同一个域中,例如,如果您尝试从
johndoe.com
向example.com
发送请求,您将收到错误,并且它的浏览器会阻止该请求!浏览器首先发出
header
请求,如果允许请求,将发出具有真实方法类型的下一个请求 .对于CodeIgniter,尝试将OPTIONS添加到允许的方法中 .
看看这个answer