Fetch PATCH Request Is Not Allowed
When integrating a React frontend with a Rails API, handling HTTP methods beyond standard GET and POST can sometimes trip up even experienced developers. You might be happily using isomorphic-fetch for your CRUD operations without issue, only to hit a wall when attempting to send a PATCH request. The browser throws an error: "Method patch is not allowed by Access-Control-Allow-Methods in preflight response."
The immediate instinct is to check the server configuration. In many cases, Rails responds with an OPTIONS request that explicitly includes PATCH in the Access-Control-Allow-Methods header. If you inspect the network tab, you will see this permission granted. However, the client-side library still rejects the request. This discrepancy often stems from a subtle but critical detail regarding HTTP method casing.
The issue lies in how isomorphic-fetch (and similar libraries like node-fetch) handle the HTTP method string passed to the fetch API. While standard HTTP methods like GET, POST, and DELETE are case-insensitive by specification, PATCH is treated differently in this specific implementation context.
If your code looks like this:
fetch(API_URL + API_PATH + 'tasks', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'patch', // Note the lowercase
body: JSON.stringify( { task: task } )
})
The library may normalize this string or pass it to a lower-level fetch implementation that strictly enforces uppercase for certain methods. Specifically, isomorphic-fetch relies on an underlying mechanism where the method type must be uppercase for specific operations to trigger the correct CORS preflight logic. When the method is lowercase (patch), the internal normalization might not align with the server's expectation of the string literal "PATCH" in the preflight handshake, causing the library to reject the request despite the server allowing it.
This behavior was flagged as a potential bug but was ultimately determined to be intended functionality within the specific version history of the library. The underlying implementation requires the method type to be case-sensitive for PATCH.
To resolve this, you must ensure the HTTP method is passed in uppercase:
fetch(API_URL + API_PATH + 'tasks', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'PATCH', // Must be uppercase
body: JSON.stringify( { task: task } )
})
This change aligns the client request with the expectations of the isomorphic-fetch implementation and the Rails server. It is a reminder that while HTTP headers are often case-insensitive, specific API specifications or library implementations can impose stricter casing rules on method types. Always verify the exact casing required by your frontend libraries when dealing with partial update operations like PATCH to avoid these elusive CORS errors.