【发布时间】: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