javascriptnode.jsaxiosfshubspot-api

Node axios not sending correct header: 'Content-Type': 'multipart/form-data'


I am attempting to upload a file using the Node example provided in the HubSpot docs.

I am receiving 415(Unsupported media type). The response says I am sending the header application/json even though I am setting multipart/form-data.

const uploadFile = async () => {    

    const postUrl = `https://api.hubapi.com/filemanager/api/v3/files/upload?hapikey=${HAPI_KEY}`;

    const filename = `${APP_ROOT}/src/Files/Deal/4iG_-_CSM_Additional_Capacity/test.txt`;

    const headers = {
        'Content-Type': 'multipart/form-data'
    }

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

    var formData = {
        file: fs.createReadStream(filename),
        options: JSON.stringify(fileOptions),
        folderPath: '/Root'
    };

    try {
        const resp = await axios.post(postUrl, formData, headers); // API request

        console.log(resp.data)
    } catch (error) {
        console.log("Error: ", error);
    }
}

Can you see what the problem is or recommend a better way of uploading the file?

Thanks!


Solution

  • The Node example you link to uses the (deprecated) request module, not Axios.

    To use Axios (source) you would rewrite that as:

    const FormData = require('form-data');
     
    const form = new FormData();
    form.append('file', fs.createReadStream(filename));
    form.append('options', JSON.stringify(fileOptions));
    form.append('folderPath', '/Root');
    
    const config = { headers: form.getHeaders() };
    
    axios.post(postUrl, form, config);