小编emi*_*nsh的帖子

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

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

从源“ http://localhost: 3000 ”访问位于“http://localhost:8080/testpost”的XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:无“访问控制” -Allow-Origin'标头存在于请求的资源上。

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

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: POST,GET, OPTIONS");
header("Access-Control-Allow-Headers: *");
Run Code Online (Sandbox Code Playgroud)

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

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

感谢您的帮助

php reactjs axios codeigniter-4

3
推荐指数
1
解决办法
2万
查看次数

标签 统计

axios ×1

codeigniter-4 ×1

php ×1

reactjs ×1