P粉5026087992023-08-25 17:38:47
In my similar case, Angular frontend and Php backend helped with the code below. First I send a header:
header("Access-Control-Allow-Origin: http://localhost:4200"); header("Content-Type: application/json; charset=UTF-8"); header("Access-Control-Allow-Methods: POST, DELETE, OPTIONS"); header("Access-Control-Max-Age: 3600"); header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
After them I can ignore option requests:
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { return 0; }
This approach helped me handle "post" and "delete" embedded request methods in Angular.
P粉3168908842023-08-25 16:25:07
Well, I had a similar problem recently and I solved it all on the backend only, without the .htaccess stuff.
When the browser sends a cross-server request, it first sends an OPTIONS request to ensure that it is valid and that a "real" request can be sent. The "real" request is sent when it gets a correct and valid response from OPTIONS.
Now, for both requests to the backend, you need to make sure the correct headers are returned: content-type, allow-origin, allow-headers, etc...
Ensure that in the OPTIONS request on the backend, the application returns the header and returns the response instead of continuing the full flow of the application.
In a "real" request you should return the correct headers and regular response body.
Example:
//The Response object $res = $app->response; $res->headers->set('Content-Type', 'application/json'); $res->headers->set('Access-Control-Allow-Origin', 'http://example.com'); $res->headers->set('Access-Control-Allow-Credentials', 'true'); $res->headers->set('Access-Control-Max-Age', '60'); $res->headers->set('Access-Control-Allow-Headers', 'AccountKey,x-requested-with, Content-Type, origin, authorization, accept, client-security-token, host, date, cookie, cookie2'); $res->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); if ( ! $req->isOptions()) { // this continues the normal flow of the app, and will return the proper body $this->next->call(); } else { //stops the app, and sends the response return $res; }
Things to remember:
If you use: "Access-Control-Allow-Credentials" = true Make sure "Access-Control-Allow-Origin" is not "*", it must be set to the correct domain! (A lot of blood was shed here :/)
Define the allow headers you will get in "Access-Control-Allow-Headers" If you don't define them, the request will fail