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

Time:02-15

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!

CodePudding user response:

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);

CodePudding user response:

Run API in Postman and check NodeJs - Axios Detail in Postman Code Snippet.

const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');

const uploadFile = async () => {
    try {
        let data = new FormData();
        data.append('folderPath', '/Root');
        form.append('file', fs.createReadStream(`${APP_ROOT}/src/Files/Deal/4iG_-_CSM_Additional_Capacity/test.txt`));
        data.append('options', JSON.stringify({
            access: 'PUBLIC_INDEXABLE',
            overwrite: false,
            duplicateValidationStrategy: 'NONE',
            duplicateValidationScope: 'ENTIRE_PORTAL'
        }));
        
        var config = {
            method: 'post',
            url: `https://api.hubapi.com/filemanager/api/v3/files/upload?hapikey=${HAPI_KEY}`,
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            data: data
        };
        
        const resp = await axios(config); // API request
        console.log(resp.data)
    } catch (error) {
        // error
    }
}
  • Related