我正在编写一个 API,其中一种方法是 POST,它处理调用中传递的数据并设置响应状态。当我从网站表单提交中调用此方法时,它工作正常,但是当我通过 cURL 从命令行进行相同的调用时,它会重定向到“/”。你知道这是为什么吗?
卷曲:
curl --location --request POST \
-H "Content-Type: application/json" \
-d '{"name":"John Doe","email":"[email protected]"}' \
-w "Status: %{http_code}" \
http://localhost:8080/api/test
方法:
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
class Api extends Controller
{
public function test()
{
$postData = $this->request->getPost();
if (!empty($postData)) {
$name = $postData['name'];
$email = $postData['email'];
echo "Received data: Name = $name, Email = $email";
$responseStatus = 'success'; // Example: 'success', 'error', etc.
return $this->response->setJSON(['status' => $responseStatus]);
} else {
return $this->response->setJSON(['status' => 'error', 'message' => 'No data received']);
}
}
}
作为参考,我在 Routes.php 中设置了这条路线:
$routes->post('api/test', 'Api::test');
我发现问题了!这是CSRF保护。我只需更新它以排除 API 调用:
public $globals = [
'before' => [
// 'honeypot',
'csrf' => ['except' => ['api/*]],
// 'invalidchars',
],
'after' => [
'toolbar',
// 'honeypot',
// 'secureheaders',
],
];