使用Multipart Form Data时遭遇CORS错误,请求排查解决
问题:FormData上传图片后,后续接口请求触发CORS错误
现有配置与代码
API端CORS配置
app.use(cors({credentials: true, origin: 'http://localhost:19006'}));
API端Multer图片上传处理代码
const storage = multer.diskStorage({ destination: (req, file, callback) => { callback(null, "avatars"); }, filename: (req, file, callback) => { let imagePath = Date.now() + path.extname(file.originalname); callback(null, imagePath); }, }); const upload = multer({ storage: storage }); app.use("/uploadAvatar", upload.single("avatar"), (req, res) => { res.status(200).json(req.file); });
前端React Native Web代码
const pickPicture = async () => { let result = await DocumentPicker.getDocumentAsync({}); const data = new FormData(); data.append("avatar", result.file); axios .post( `${BASE_URL}/uploadAvatar`, data, { withCredentials: true, headers: { "Content-Type": "multipart/form-data", }, } ) .catch(function (error) { console.log(error); }) .then(async function (res) { let token = await AsyncStorage.getItem("token"); let picture = res.data.filename; axios .post( `${BASE_URL}/userData/update`, { token: token, picture: picture, }, { withCredentials: true, headers: { "Content-Type": "application/json; charset=UTF-8", }, } ) .catch(function (error) { console.log(error); }); setUserAvatar(picture); AsyncStorage.setItem("avatar", picture); }); };
错误信息
Access to XMLHttpRequest at 'https://myApi/userData/update' from origin 'http://localhost:19006' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
排查与解决方向
- 确认CORS中间件加载顺序:必须保证
app.use(cors(...))在所有路由(包括/userData/update)之前执行。如果/userData/update路由定义在CORS中间件前面,该接口的响应就不会携带CORS头,直接触发错误。 - 检查
/userData/update路由的特殊处理:如果该接口有自定义中间件(比如权限校验、错误捕获),要确保这些中间件没有覆盖或移除CORS响应头。例如错误处理中间件直接返回响应但未设置CORS头,也会导致问题。 - 验证origin匹配情况:打印API端的
req.headers.origin,确认实际请求的origin是否和配置的http://localhost:19006完全一致,避免环境变量或动态origin逻辑导致的不匹配。 - 预检请求(OPTIONS)处理:虽然cors中间件会自动处理OPTIONS请求,但如果服务器有自定义的OPTIONS路由逻辑,可能会覆盖默认处理。检查是否存在针对
/userData/update的OPTIONS请求处理,确保返回正确的CORS头。 - 确认凭证头一致性:所有带
withCredentials: true的请求,API端必须返回Access-Control-Allow-Credentials: true头。你的CORS配置已设置credentials: true,但要确保/userData/update的响应确实携带了这个头。
内容的提问来源于stack exchange,提问作者Myrmelo
相关产品推荐
相关产品推荐

