Opened 8 years ago
Closed 8 years ago
#37994 closed defect (bug) (fixed)
Preflight CORS check fails because of missing "Access-Control-Allow-Headers: Content-Type"
Reported by: |
|
Owned by: |
|
---|---|---|---|
Milestone: | 4.7 | Priority: | normal |
Severity: | normal | Version: | 4.4 |
Component: | REST API | Keywords: | has-patch |
Focuses: | Cc: |
Description
Working on a single page app in Angular2 (Ionic 2), and trying to talk to the WP REST API V2.
GETs work fine, but when I try to POST, the preflight check fails because of a missing Access-Control-Allow-Headers returned from WP REST.
The preflight check checks for Access-Control-Request-Headers: Authorization, Content-Type
with an OPTIONS call, and WP REST replies:
Access-Control-Allow-Headers: Authorization
The missing "Content-Type" from the reply, blocks the following post-flight request, and execution stops.
I can easily solve this problem with some custom headers via PHP, but I simply request that you add official support for this. Would be a lot less hassle for a lot of Javascript based apps.
Basically the only thing you need to add is "Content-Type" to line 237 of /wp-includes/rest-api/class-wp-rest-server.php.
Anyway, here's a workaround:
<?php add_filter('rest_post_dispatch', function (\WP_REST_Response $result) { if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { $result->header('Access-Control-Allow-Headers', 'Authorization, Content-Type', true); } return $result; });
Still, would prefer official support for it.
We're currently patching this on WordPress.com - otherwise POST/PUT requests with
Content-Type: application/json
fail because they are not "simple requests" according to the CORS rules. We should fix this in core instead of making people patch around it.