2023-03-24

fetch() POST request returns "Error 415 Unsupported Media Type"

When trying to upload a PDF file using fetch(), I keep getting a 415 error. The PDF file is saved in the same directory as the js file, and the name is definitely correct.

async function uploadFile(filePath, extension, timestamp) {

    const url = "https://api.hubapi.com/files/v3/files";
    // const url = "https://api.hubapi.com/filemanager/api/v3/files/upload"; // also doesn't work.
    var filename = `${filePath}.${extension}`;

    var fileOptions = {
        access: 'PRIVATE',
        overwrite: false,
        duplicateValidationStrategy: 'NONE',
        duplicateValidationScope: 'ENTIRE_PORTAL'
    };

    var formData = {
        file: fs.createReadStream(filename),
        fileName: `${filename} (${timestamp}).${extension}`,
        options: JSON.stringify(fileOptions),
        folderPath: 'Quotations'
    };

    try {
        const response = await fetch(url, { 
            "method": "POST",
            "formData": formData,
            "headers": {
                'Authorization': `Bearer ${process.env.ACCESS_TOKEN}`,
                "Content-Type": "application/pdf"
            }
        });

        if(!response.ok) {
            throw new Error(`Error. Response not ok: ${response.status}`);
        }
        
        const data = await response.json();
        return data;

    } catch(error) {
        console.log(`Error: ${error}`);
    }

}

const fileId = uploadFile("Quotation", "pdf", getCurrentTimestamp());
fileId.then((data) => console.log(data));

I have tried changing the "Content-Type" in headers to several different options, and all spit back 400 and 415 errors:

"Content-Type": "multipart/form-data" - "Error: Error: HTTP Error: 400".

"Content-Type": "application/json" - "Error: Error: HTTP Error: 415".

"Content-Type": "text/plain" - "Error: Error: HTTP Error: 415".

Excluding "Content-Type" returns - "Error: Error: HTTP Error: 400".

When I use request.post() instead of fetch(), I can upload the file. But I want to use fetch().



No comments:

Post a Comment