1
var formData = {
  name: 'TestDeck',
  description: 'This is a test deck for my api',
  private: false,
  shareable: false,
  ttsLanguages: [],
  blacklistedSideIndices: [],
  blacklistedQuestionTypes: [],
  gradingModes: [],
  imageAttribution: 'https://www.logogarden.com/wp-content/uploads/lg-index/Example-Logo-6.jpg',
  imageFile: fs.readFile('retext.png', 'utf8')
}

function createDeck(connection) {
  request.post({
      url: '<url>',
      formData: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      json: true
    }),
    function(err, resp, body) {

    }
}

I am getting the error: TypeError: First argument must be a string or Buffer.

I honestly have no idea why, need help.

1
  • fs.readFile is an asynchronous method, so imageFile most likely isn't what you think it is Commented Sep 9, 2017 at 19:59

1 Answer 1

5

There are several problems in the code.

  1. You get TypeError: First argument must be a string or Buffer because you are trying to send boolean value false in form data -- HTML form does not support boolean value. In HTML, checked checkbox will send its value, while unchecked checkbox won't.

    To fix the issue, you can change false to 'FALSE'(string) and parse it in server side.

  2. The use of fs.readFile('retext.png', 'utf8') is incorrect. To attach file in the form, the right way is: imageFile: fs.createReadStream('retext.png').

  3. When formData: formData is used in request.post(...), the Content-Type of the HTTP request would be multipart/form-data automatically, you don't need to define Content-Type header again.

    Moreover, it is incorrect to set json: true, which will make Content-Type as application/json. This conflict will make request module confused, and may cause problem in some JavaScript environment.

  4. The callback function function(err, resp, body){...} should be part of request.post(...), maybe it is a typo.

In summary, the correct code would look like:

var formData = {
  name: 'TestDeck',
  description: 'This is a test deck for my api',
  private: 'FALSE',
  shareable: 'FALSE',
  ttsLanguages: [],
  blacklistedSideIndices: [],
  blacklistedQuestionTypes: [],
  gradingModes: [],
  imageAttribution: 'https://www.logogarden.com/wp-content/uploads/lg-index/Example-Logo-6.jpg',
  imageFile: fs.createReadStream('retext.png')
}

function createDeck(connection) {
  request.post({
    url: '<url>',
    formData: formData
  }, function(err, resp, body) {

  })
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, just what I needed
you saved my day. I was appending boolean value in it. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.