mostpros1 / repository

3 stars 1 forks source link

CORS error #681

Open TimHei123 opened 1 month ago

TimHei123 commented 1 month ago

I am receving a CORS error when trying to send files to s3.

what have I done? I have made an api gateway connected to a lambda function to store documents in s3 and send a link to that bucket so that I can send the files via chat.

what is the intended result? the intended result is that the file I upload should be converted to base64string which works as intended. it should then be sent via the url to the api in following manner: /chatuploads/{base64data} . the api should return the path of the s3 bucket and it should be printed to the console for further processing.

this is the code that make the api call:`const handleUpload = async () => { // Check if a file is selected before proceeding if (!selectedFile) { console.error("No file selected"); return; }

function getBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });
}

// Convert the selected file to Base64
const base64Data = await getBase64(selectedFile);

// Extract the file name from the selectedFile object
const fileName = selectedFile.name;

// Prepare the fileData string according to your backend's expectations
const fileData = "S3" + fileName + "!" + base64Data.split(',')[1];

try {
    // Send the fileData to your backend
    const Data = encodeURIComponent(fileData);
    console.log("Data ", Data)
    const response = await fetch(`https://rfzmb9ibkk.execute-api.eu-north-1.amazonaws.com/chatuploads/${Data}`);

    if (!response.ok) {
        throw new Error(`HTTP error status: ${response.status}`);
    }

    const responseData = await response.json(); // Assuming the response is JSON
    console.log(responseData); // Handle the response data as needed

} catch (err) {
    console.error(err);
}

};`

what is the actual result? the actual result is Error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://rfzmb9ibkk.execute-api.eu-north-1.amazonaws.com/chatuploads/S3stripe-icon.png!iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAkFBMVEVjW%2F%2F%2F%2F%2F9hWf97dP9fV%2F9bUv9dVf9ZUP9XTv%2F9%2Ff%2F4%2BP%2F7%2B%2F9lXf%2Ft7P%2Bhnf%2BHgf90bf%2Fz8v%2BSjf%2Fi4f%2Fo5%2F%2BAev%2BXkv%2Bemv%2BPiv%2Ff3f%2B9u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DedJIniOEo6A7%2Beir2dH7i9u336%2BPGbeWB4xxEEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEav4DJRlZ%2BBCLXEYAAAAASUVORK5CYII%3D. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 404.

wierd fact: if I just give the file name, for example test.png, and not a base64 string in the url, then I get error code 500 because the api is expecting a base64 string and not text.

how to reproduce this result:

pull Brach to your local machine. run npm install run amplify pull --appId d2j290dx5bs7ht --envName acceptance run npm run start:frontend go to the login page at /nl/login login using the email timon.heidenreich@icloud.com and the password is Longpass next go to the chat page at /nl/homeowner-dashboard/chat click on the chat with the name timon.heidenreich click on the paperclip and in the menu click on the first button which looks like a folder choose any image or file you want from your computer. click on the upload button just under the folder icon now open your console and you should see the error.

stefanhopman1 commented 1 month ago

https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cors.html

OmkumarMangukiya commented 1 month ago

Try this const cors = require('cors');

app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); // Allow requests from your frontend res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); // Allow specific HTTP methods res.header('Access-Control-Allow-Headers', 'Content-Type'); // Allow specific headers next(); }); cors is a security feature used by browser this will just disable it.