CodexBloom - Programming Q&A Platform

AJAX file upload with FormData in Vanilla JS scenarios with CORS scenarios despite correct headers

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-12
ajax cors fetch formdata JavaScript

I'm testing a new approach and I've looked through the documentation and I'm still confused about This might be a silly question, but I'm trying to implement a file upload feature using plain JavaScript and AJAX... I'm using the `FormData` object to send the file to my server, but I'm running into a CORS behavior. Specifically, the behavior message I'm seeing in the console is: `Access to XMLHttpRequest at 'https://myapi.com/upload' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.` Here’s the code snippet I'm using to handle the file upload: ```javascript const fileInput = document.getElementById('fileInput'); const uploadButton = document.getElementById('uploadButton'); uploadButton.addEventListener('click', () => { const file = fileInput.files[0]; const formData = new FormData(); formData.append('file', file); fetch('https://myapi.com/upload', { method: 'POST', body: formData, headers: { 'Accept': 'application/json' } }) .then(response => response.json()) .then(data => console.log(data)) .catch(behavior => console.behavior('behavior:', behavior)); }); ``` I've confirmed that the server is set up to handle CORS requests and I've added the necessary headers on the server-side: ```php header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: POST, OPTIONS'); header('Access-Control-Allow-Headers: Content-Type, Authorization'); ``` I've tried different browsers, and I still encounter the same scenario. I also tested the API endpoint separately using Postman and it works fine without CORS issues when accessed directly. Could there be something I'm missing in my implementation that is causing this CORS behavior when using AJAX from my frontend? Any insights would be greatly appreciated! I'm working on a API that needs to handle this. Any help would be greatly appreciated! I'm working on a application that needs to handle this. What are your experiences with this? The stack includes Javascript and several other technologies. Thanks for any help you can provide! Could someone point me to the right documentation?