我正在使用 Codeigniter 4 为反应应用程序制作 api。在邮递员中一切正常,但是当我使用 axios 发出请求(也尝试过 fetch)时,它会出现 CORS 错误
从源“ 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: *");
现在它适用于没有 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');
}
谢谢你的帮助