0

There is an external (I can't change it) API for creating articles. Using this API I succeed create an article this way:

curl -F "article[id]=607822" -F "article[file]=@/article_file_example/article" 'https://api/v2/articles'

How can I perform this following http request using Node.js (preferably with axios)?

The code should work for both Linux and Windows, so I can't use require('child_process').exec

I tried the following:

    const formData = {
        'id': 607822,
        file: fs.createReadStream(filePath), //filePath is the absolute path to the file
    };

    axios.post('https://api/v2/articles', {article: formData});

But the API response is validation error, which means I didn't succeed to imitate the curl command.

Any suggestions?

P.S. There is also an impovement I would like to perform once I have a working solution. I have the file content, so I prefer to send it directly without creating the file + createReadStream. I tried to do that Blobing the context, but didn't succeed.

Alexander
  • 7,484
  • 4
  • 51
  • 65

1 Answers1

0

Looks like axios doesn't support sending multipart/form-data: https://github.com/mzabriskie/axios/issues/789

My solution was based on one of the answers for: Nodejs POST request multipart/form-data

I used restler module.

I couldn't send my data just as:

{
    article: {
        'id': 607822,
        file: restler.file(filePath, null, stats.size, null, "text/plain")
    }
}

since it wasn't retrieved correctly by server.

So I had to transform it to:

{
    'article[id]': 607822,
    'article[file]': restler.file(filePath, null, stats.size, null, "text/plain")
}
Alexander
  • 7,484
  • 4
  • 51
  • 65