Vanilla PHP API仅允许POST请求配置问题:已设置CORS头仍可接收任意请求,如何解决?
Hey there! I see you’ve set up CORS headers, but you’re still able to send other request types to your API. Let’s clear up a key point first: CORS headers are enforced by browsers, not your server. They prevent browsers from making unauthorized cross-origin requests, but they don’t stop tools like Postman or direct server-to-server calls from sending non-POST requests. To truly restrict your API to only accept POST, you need to add server-side validation.
Here’s a straightforward, effective solution:
1. Handle the OPTIONS Preflight Request
Browsers send an OPTIONS request before cross-origin POST requests (especially if the request includes custom headers) to check if the server allows the actual POST. You need to respond to this properly to avoid cross-origin errors.
2. Validate the Request Method Directly
Check the incoming request method using $_SERVER['REQUEST_METHOD']. If it’s not POST, return a 405 Method Not Allowed status code and a clear error message to block the request.
Full Working Code Example
// First, handle the OPTIONS preflight request if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { // Send required CORS headers header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); header("Access-Control-Allow-Methods: POST"); header("Access-Control-Allow-Headers: Access-Control-Allow-Headers, Content-Type, Access-Control-Allow-Methods, Authorization, X-Requested-With"); header("Access-Control-Max-Age: 3600"); // Cache preflight response for 1 hour http_response_code(204); // No content response (standard for preflight) exit(); } // Now, enforce only POST requests are processed if ($_SERVER['REQUEST_METHOD'] !== 'POST') { // Send CORS headers so cross-origin clients receive the error header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); http_response_code(405); // Method Not Allowed status code echo json_encode(['error' => 'Only POST requests are permitted']); exit(); } // Your POST request handling logic goes here // Example: // $input = json_decode(file_get_contents('php://input'), true); // Process the input and send a response echo json_encode(['message' => 'POST request received successfully']);
Why This Works
- The OPTIONS handler ensures browsers get the green light for valid cross-origin POSTs without triggering errors.
- The
REQUEST_METHODcheck blocks any non-POST request from reaching your core API logic—whether it’s coming from a browser, Postman, or another server. - Returning the
405status code follows HTTP standards, making your API behavior consistent and predictable for all clients.
内容的提问来源于stack exchange,提问作者user14142616




