Isomorphic Fetch结合FormData请求时的两类异常行为咨询
Let's break down your two problems and fix them step by step, like a fellow developer would:
1. Why credentials: 'include' fails to send cookies (same-origin scenario)
First off, credentials: 'include' is built for cross-origin requests (think frontend on app.example.com and backend on api.example.com). For same-origin setups (both frontend and backend on the same server/domain), credentials: 'same-origin' is the correct, intended setting.
The reason include isn't working here is likely because isomorphic-fetch handles same-origin credential logic differently than cross-origin. Ditch include for your setup—it's overkill and causing unexpected behavior.
2. Why credentials: 'same-origin' isn't passing the file
This almost always traces back to one of two common mistakes with FormData and fetch:
Mistake 1: Manually setting the Content-Type header
When you send a FormData object, the browser (and isomorphic-fetch) automatically generates the correct multipart/form-data header with a boundary string—this string tells the backend how to split apart form fields and files. If you manually set headers: { 'Content-Type': 'multipart/form-data' }, you're stripping out this critical boundary, so the backend can't parse the file at all.
Mistake 2: Incorrect FormData construction
Double-check that you're appending your File object properly. Including the filename as the optional third parameter helps the backend recognize the file type correctly:
formData.append('file', yourFileObject, 'profile-pic.jpg');
Fixed Working Example
Here's a corrected implementation that should handle both cookies and file uploads smoothly:
import fetch from 'isomorphic-fetch'; // Build your FormData correctly const uploadForm = new FormData(); uploadForm.append('file', userFile, userFile.name); // Use the file's original name uploadForm.append('uploaderId', '12345'); // Add extra fields if needed // Send the request fetch('/your-upload-endpoint', { method: 'POST', credentials: 'same-origin', // Correct for same-server requests body: uploadForm // Let fetch handle the Content-Type automatically }) .then(res => { if (!res.ok) throw new Error('Upload failed'); return res.json(); }) .then(data => console.log('Upload successful:', data)) .catch(err => console.error('Upload error:', err));
Quick Bonus Check
Older versions of isomorphic-fetch had bugs with FormData handling in certain environments (like Node.js or legacy browsers). Upgrade to the latest version to rule out version-specific issues:
npm update isomorphic-fetch
内容的提问来源于stack exchange,提问作者Reck

