带有codeigniter的Angular 4 Http请求与CORS发生API错误,无法访问API函数

o4tp2gmn  于 2022-12-06  发布在  Angular
关注(0)|答案(3)|浏览(184)

我在localhost(xampp)/ codeigniter上有api,我试图通过angular 4访问它,浏览器一直在控制台中显示此错误。api在postman中工作正常。
【火狐】:
已阻止跨源请求:同源策略不允许阅读位于http://lvh.me/ci-abc/api/get_alltasks的远程资源。(原因:CORS标头“访问控制-允许-来源”缺失)。
【 chrome 色】:
无法加载http://lvh.me/ci-abc/api/get_alltasks:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问源“http://localhost:4200”。
我试过将API网址改为localhost和127.0.0.1,但没有成功。我是一个初学者,所以请原谅我,如果我错过了什么。
Angular 4中的服务功能

gettasks()
  {
    return this.http.get('http://lvh.me/ci-abc/api/get_alltasks')
    .map(res=>res.json());
  }

代码点火器中的API函数

function get_alltasks_get()
    {
        {
            $result = $this->todo_model->get_alltasks();

            if ($result) {
                $this->response($result, 200);
            } else {
                $this->response("No record found", 404);
            }
        }
    }
x6492ojm

x6492ojm1#

这不是Angular 问题,问题的原因是因为你不是在同一个域作为您的服务器是,例如,如果你试图发送一个请求到example.comjohndoe.com你会得到错误,它的浏览器阻止了请求!
浏览器首先发出一个header请求,如果该请求被允许,则将发出下一个具有真实的方法类型的请求。
对于CodeIgniter,请尝试将OPTIONS添加到允许的方法中。

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

看看这个answer

wz8daaqr

wz8daaqr2#

基于PHP的CORS

浏览器会为从XMLHttpRequestFetch API中发起的跨站点请求发送特定的HTTP headers。它还希望看到与跨站点响应一起发回的特定HTTP头。
这些头文件的概述,包括启动请求和处理来自服务器的响应的示例JavaScript代码,以及对每个头文件的讨论,can be found in the HTTP Access Control (CORS)文章和应作为本文的配套文章阅读。
并且应该作为本文的配套文章来阅读。This article介绍了如何用PHP处理访问控制请求和制定访问控制响应
如果你没有权限配置Apache,你仍然可以从PHP脚本中发送头文件。在PHP脚本中添加以下代码:

<?php
header("Access-Control-Allow-Origin: *");
unhi4e5o

unhi4e5o3#

我花了些时间在这上面,我发现了一些事情:

  • 从研究你的请求开始,从Angular 到后端.在请求头中有一个键叫做“origin:......“这就是所要求的起源。
  • Codeigniter使用了一个叫做“过滤器”的概念,它可以与laravel的中间件或angulas拦截器相比较。它们对请求做一些事情。在这个例子中,添加一个头。
  • 您需要在Config/Filters.php中注册这些过滤器,以便应用程序使用它们。

所以我是这么做的:

  • 在App\Filters下创建一个新的CorsFilter.php
use CodeIgniter\config\Services;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\Response;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;

class CorsFilter implements FilterInterface
{
    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {

    }

    public function before(RequestInterface $request, $arguments = null)
    {
        if (array_key_exists('HTTP_ORIGIN', $_SERVER)) {
            $origin = $_SERVER['HTTP_ORIGIN'];
        } else if (array_key_exists('HTTP_REFERER', $_SERVER)) {
            $origin = $_SERVER['HTTP_REFERER'];
        } else {
            $origin = $_SERVER['REMOTE_ADDR'];
        }
        $allowed_domains = array(
            'http://localhost:4200',
            // your origin from request headers goes here
        );

        if (in_array($origin, $allowed_domains)) {
            header('Access-Control-Allow-Origin: ' . $origin);
        }
        //these headers are always needed for an api call
        header("Access-Control-Allow-Headers: Origin, X-API-KEY, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Headers, Authorization, observe, enctype, Content-Length, X-Csrf-Token");
        header("Access-Control-Allow-Methods: GET, PUT, POST, DELETE, PATCH, OPTIONS");
        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Max-Age: 3600");
        header('content-type: application/json; charset=utf-8');
        $method = $_SERVER['REQUEST_METHOD'];
        //this handles the required 'ok' for the preflight check
        if ($method == "OPTIONS") {
            header("HTTP/1.1 200 OK CORS");
            die();
        }

    }

}

在App\config\Filters.php中注册过滤器

namespace Config;

use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Filters\CSRF;
use CodeIgniter\Filters\DebugToolbar;
use CodeIgniter\Filters\Honeypot;
use CodeIgniter\Filters\InvalidChars;
use CodeIgniter\Filters\SecureHeaders;
use App\Filters\CorsFilter;

class Filters extends BaseConfig
{
    /**
     * Configures aliases for Filter classes to
     * make reading things nicer and simpler.
     *
     * @var array
     */
    public $aliases = [
        'csrf'          => CSRF::class,
        'toolbar'       => DebugToolbar::class,
        'honeypot'      => Honeypot::class,
        'invalidchars'  => InvalidChars::class,
        'secureheaders' => SecureHeaders::class,
        'cors'          => CorsFilter::class
    ];

    /**
     * List of filter aliases that are always
     * applied before and after every request.
     *
     * @var array
     */
    public $globals = [
        'before' => [
            'cors'
            // 'honeypot',
            // 'csrf',
            // 'invalidchars',
        ],
        'after' => [
            'toolbar',
            // 'honeypot',
            // 'secureheaders',
        ],
    ];

    /**
     * List of filter aliases that works on a
     * particular HTTP method (GET, POST, etc.).
     *
     * Example:
     * 'post' => ['foo', 'bar']
     *
     * If you use this, you should disable auto-routing because auto-routing
     * permits any HTTP method to access a controller. Accessing the controller
     * with a method you don’t expect could bypass the filter.
     *
     * @var array
     */
    public $methods = [];

    /**
     * List of filter aliases that should run on any
     * before or after URI patterns.
     *
     * Example:
     * 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']]
     *
     * @var array
     */
    public $filters = [];
}

现在每个来自前端的请求都被允许进入后端。希望这是有意义的,并帮助任何在这方面挣扎的人。

相关问题