2

I am learning and experimenting on NodeJs. I am using request-promise to call another api from NodeJs. I am using form-data to create a form and send it to another api. My snippet:

const requestPromise = require('request-promise');
const FormData = require('form-data');
....

var sendToAPI = async (fileObjBuffer, myId, timestamp) => {

    let formData = new FormData();
    formData.append('fileData', fileObjBuffer);
    formData.append('myId', myId);
    formData.append('fileName', timestamp);

    let options = {
        method: 'POST',
        uri: '<URL>',
        formData: formData,
        headers: {
            'Access-Control-Allow-Origin': '*',
            'enctype': 'multipart/form-data',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Methods': 'GET,POST,OPTIONS,DELETE,PUT'
        },
        json: true
    };
    try {
        let apiResult = await requestPromise(options).promise();
        console.log('\n\napiResult: ', apiResult);
    } catch (error) {
        console.log('error in sending to api: ',error);
    } 
}

var fetchAllData = async () => {
    let query = 'select * from demo_db.demo_table;';
    let fileObject = "";
    var result;
    try {
        //cassandra query
        result = await client.execute(query, [], { prepare: true });
    } catch (error) {
        console.log('error in fetching data from Cassandra: ',error);
    }
    result.rows.forEach(resultObj => {
        fileObject = fileObject +resultObj['room_id'] +":"+resultObj['message_id']+":"+resultObj['original_message'] +":"+resultObj['send_date'] +":"+  resultObj['sender'] +"%";
    });
    let fileObjBuffer = new Buffer(fileObject);
    let myId = uuidv4();
    let timestamp = date.format(new Date(), 'YYYYMMMDDhhmmss', false);  
    sendToAPI(fileObjBuffer,myId,timestamp);
}

My error:

error in sending to api:  TypeError: Cannot read property 'name' of null
at FormData._getContentDisposition (/home/bhushan/NodeJS-Scheduler/node_modules/request/node_modules/form-data/lib/form_data.js:226:40)
at FormData._multiPartHeader (/home/bhushan/NodeJS-Scheduler/node_modules/request/node_modules/form-data/lib/form_data.js:177:33)
at FormData.append (/home/bhushan/NodeJS-Scheduler/node_modules/request/node_modules/form-data/lib/form_data.js:70:21)
at appendFormValue (/home/bhushan/NodeJS-Scheduler/node_modules/request/request.js:326:21)
at Request.init (/home/bhushan/NodeJS-Scheduler/node_modules/request/request.js:337:11)
at Request.RP$initInterceptor [as init] (/home/bhushan/NodeJS-Scheduler/node_modules/request-promise-core/configure/request2.js:45:29)
at new Request (/home/bhushan/NodeJS-Scheduler/node_modules/request/request.js:127:8)
at request (/home/bhushan/NodeJS-Scheduler/node_modules/request/index.js:53:10)
at sendToAPI (/home/bhushan/NodeJS-Scheduler/schedulerTest.js:52:25)
at fetchAllData (/home/bhushan/NodeJS-Scheduler/schedulerTest.js:95:2)
at process._tickCallback (internal/process/next_tick.js:68:7)

Please help me to solve this issue.

benomatis
  • 5,536
  • 7
  • 36
  • 59
Bhushan Mahajan
  • 131
  • 3
  • 13
  • The code what you have pasted doesn't contain the error part. The error states that `name of null` means you are trying to access name of `null` which may be an object or array, so paste your full code otherwise its difficult – Subburaj Dec 30 '19 at 08:25
  • See https://stackoverflow.com/questions/44597174/form-data-library-throwing-cannot-read-property-of-null-error-when-trying-append –  Dec 30 '19 at 08:29
  • @Subburaj, I have just written another simple function `fetchAllData` to create `fileName`, `myId`, and `fileObjBuffer` values and then called `sendToAPI()` from `fetchAllData`. – Bhushan Mahajan Dec 30 '19 at 08:34
  • Hi, @VictorF, I have seen the post but I didn't understand, how to implement it in my case. – Bhushan Mahajan Dec 30 '19 at 08:38
  • Is this all of your code? –  Dec 30 '19 at 08:39
  • @VictorF, actually, there is another function `fetchAllData` which creates `fileName`, `myId`, `fileObjBuffer` values. From `fetchAllData`, I am calling `sendToAPI()`. I checked `fetchAllData` function but there nothing like `name`. – Bhushan Mahajan Dec 30 '19 at 08:42
  • Hm. Sound weird. Could you try posting that function, please? –  Dec 30 '19 at 08:48
  • @VictorF I have edited the question have a look. – Bhushan Mahajan Dec 30 '19 at 09:54
  • search in your project where you have used the name property. Then post that part of code so it will be easy for community to help you out. – Sunny Parekh Dec 30 '19 at 10:18

3 Answers3

1

request-promise internally handles form-data. Therefore no need to use form-data explicitly. Instead I made normal object in following way:

var formData = {
    fileData: {
        value: fileObjBuffer,
        filename: timestamp
    },
    fileName: timestamp,
    myId: myId
}
Bhushan Mahajan
  • 131
  • 3
  • 13
0

This issue arises because in the formData key of requestPromise method you do not need to actually pass formData but an object.

request-promise internally creates formData from the object passed.

let formData = {
  fileData: fileObjBuffer,
  fileName: timestamp,
  myId: myId
}

let options = {
    method: 'POST',
    uri: '<URL>',
    formData: formData, // formData here is an object
    headers: {
        'Access-Control-Allow-Origin': '*',
        'enctype': 'multipart/form-data',
        'Content-Type': 'application/json',
        'Access-Control-Allow-Methods': 'GET,POST,OPTIONS,DELETE,PUT'
    },
    json: true
};
Achal Gupta
  • 424
  • 4
  • 15
0

I did not find any good solution. So, I have added a function which will test if the value is empty or not. if it is empty then don't add it into the formData object else add it.

const FormData = z.require('form-data');

const form = new FormData();

const addFormData = (key, value) => {
    
  // If value is an array
  if(Array.isArray(value) && value.length > 0) {
    form.append(key, JSON.stringify(value));
    return;
  }
  
  // If value is string or number
  if(value) {
    form.append(key, value);
  }
  
  // TODO: You can add aditional checks if you would like to verify if it is non-empty object etc
  
} 

addFormData('name', 'Rahul')
addFormData('age', 28)
benomatis
  • 5,536
  • 7
  • 36
  • 59
Akshoy
  • 177
  • 1
  • 4