codeigniter 4 中的 CORS 问题:对预检请求的响应未通过访问控制检查

CORS issue in codeigniter 4: Response to preflight request doesn't pass access control check

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

Access to XMLHttpRequest at 'http://localhost:8080/testpost' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

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

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

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

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');
}

感谢您的帮助

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

#Redirect for CORS Preflight request
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$  [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!

如果问题是因为 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 文件。