【问题标题】:Where to put headers in CodeIgniter 4 as API?在 CodeIgniter 4 中将标头作为 API 放在哪里?
【发布时间】:2022-01-04 22:25:08
【问题描述】:

我正在向使用 CodeIgniter 4 构建的 API 发送跨源请求。 请求来自 axios.post() 使用 React。

作为使用content-type application/json的axios.post,请求并不简单,它发送了一个preflight / options请求。

现在我明白了

No 'Access-Control-Allow-Origin' header is present on the requested resource.

我将以下内容添加到我的app/Controllers/Basecontroller.php

<?php

namespace App\Controllers;

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Authorization, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
    die();
}

// ...

但这并不能解决我的问题。

我现在想知道放置标题的最佳位置是什么?

另外,为什么我要问,我有不同的控制器用于不同的目的,一个应该允许放置和删除,另一个不应该。

【问题讨论】:

    标签: php codeigniter cors preflight


    【解决方案1】:

    我通常创建一个负责处理 CORS 问题的过滤器,在我的情况下,我全局使用该过滤器,但您只能在您喜欢的端点上使用它,它通常看起来像这样:

     *
     * @param RequestInterface $request
     * @param array|null       $arguments
     *
     * @return mixed
     */
     public function before(RequestInterface $request, $arguments = null)
    {
        $method = $_SERVER['REQUEST_METHOD'];
        header('Access-Control-Allow-Origin: --YOUR IP OR DOMAIN HERE--');
        if ($method == "OPTIONS") {
            header("HTTP/1.1 200 OK");
            header("Access-Control-Allow-Origin: --YOUR IP OR DOMAIN HERE--");
            header('Access-Control-Allow-Headers: authorization, content-type, timeout');
            --YOU CAN ADD OR REMOVE HEADERS BASED ON YOUR NEEDS--
            die();
        }
    }
    
    /**
     * Allows After filters to inspect and modify the response
     * object as needed. This method does not allow any way
     * to stop execution of other after filters, short of
     * throwing an Exception or Error.
     *
     * @param RequestInterface  $request
     * @param ResponseInterface $response
     * @param array|null        $arguments
     *
     * @return mixed
     */
    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        //
    }
    
    • 有关 CI4 过滤器的更多信息,请参阅:CI4 Filters
    • 有关 CORS 错误的更多信息,请参阅:CORS Errors

    【讨论】:

    • 我将您的过滤器添加到我的应用程序并将其应用于$globals 列表以对其进行测试。它正在调用过滤器,但没有解决预检问题。
    • 是 CORS 错误:请求的资源上不存在“Access-Control-Allow-Origin”标头。 ,还是变了?
    • 是的,同样的错误
    • 顺便说一句:我没有放置我的域,而是添加了 *
    猜你喜欢
    • 2015-12-12
    • 2021-10-06
    • 2014-02-17
    • 1970-01-01
    • 2012-02-23
    • 2011-11-28
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    相关资源
    最近更新 更多