【问题标题】:CORS issue in codeigniter 4: Response to preflight request doesn't pass access control checkcodeigniter 4 中的 CORS 问题:对预检请求的响应未通过访问控制检查
【发布时间】:2020-09-07 13:28:24
【问题描述】:

我正在使用 Codeigniter 4 为反应应用程序制作 api。在邮递员中一切正常,但是当我使用 axios 发出请求(也尝试过 fetch)时,它会出现 CORS 错误

从源“http://localhost:3000”访问“http://localhost:8080/testpost”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头出现在请求的资源上。

我尝试将标头添加到基本控制器:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: POST,GET, OPTIONS");
header("Access-Control-Allow-Headers: *");

现在它可以很好地处理没有 JSON 正文的请求,但是当我发送 json 正文时会出现同样的错误。

axios.post("http://localhost:8080/testpost", { data: "test" })
    .then((response) => {
        console.log(response);
    })
    .catch((err) => {
        console.log("error!!!");
    });
// Routes.php
$routes->post('/testpost', 'Home::testPost');
// Home Controller
public function testPost()
{
    return $this->response->setJSON('test response');
}

感谢您的帮助

【问题讨论】:

    标签: php reactjs axios codeigniter-4


    【解决方案1】:

    请尝试将 Apache 响应标头和重定向方法设置为www/public 目录根目录下的.htaccess,如下所示:

    #Redirect for CORS Preflight request
    RewriteCond %{REQUEST_METHOD} OPTIONS
    RewriteRule ^(.*)$ $1 [R=200,L]
    #Set headers to access CORS Requests / allowing localhost only
    Header always add Access-Control-Allow-Origin "*"
    Header always add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
    Header always add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
    

    注意:小心将Header always add Access-Control-Allow-Origin "*" 添加到您的.htaccess"*" 为攻击者打开大门,将* 替换为您的域或subdumain!

    【讨论】:

    • 这个方案有问题吗?
    • 感谢您的回复,不幸的是它不起作用。它的作用与在 PHP 中设置标题相同。
    • 如果完成了,请您将其标记为“完成”吗?
    • 谢谢,现在可以了。我希望有一种 PHP 方式来解决这个问题。但目前我认为这是最好的方法。
    • @ron_g ,您必须将这些行添加到您的根公共路径中的 .htaccess 文件中。并注意不要重复前 3 行。
    【解决方案2】:

    如果问题是由于www.yourdomain.com 导致字体被阻止,则将这些行放入您的 .htaccess 文件中

    # Rewrite "www.example.com -> example.com"
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
    

    CodeIgniter 的默认文件夹已经包含完整的 .htaccess 文件。

    【讨论】:

      猜你喜欢
      • 2019-12-02
      • 2019-09-09
      • 2019-01-04
      • 1970-01-01
      • 2020-08-14
      • 2021-09-26
      • 2017-11-09
      • 1970-01-01
      • 2017-04-28
      相关资源
      最近更新 更多