Wednesday, 7 June 2017

Post form with file using Node.js

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.



via Alexander

No comments:

Post a Comment