LoginSignup
10
4

More than 3 years have passed since last update.

Node.jsから画像をmultipart/form-dataでPOSTするメモ (axios利用)

Last updated at Posted at 2019-12-12

某APIを試していて、少しハマったのでメモ。
axiosで画像POSTとかを調べると、最近はVue.jsだったりフロントエンド側からPOSTする記事が多く、Node.js側から送るサンプルはあまりヒットしない印象です。

環境

Node.js v13.2.0

準備

mkdir myapp
cd myapp
npm init -y
npm i axios form-data

こんな感じでaxiosとform-dataを追加インストールです。

コード

post.js
'use strict';

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

const url = `https://hogehoge.com/hogehoge`; //ポスト先のエンドポイントURL
const imagePath = `./public/image.png`; //画像のパス
const file = fs.createReadStream(imagePath);

const form = new FormData();
form.append('image', file);

const config = {
    headers: {
        'X-HOGEHOGE-HEADER': 'xxxxxxx', //APIごとのヘッダーなど
        ...form.getHeaders(),
    }
}

axios.post(url, form, config)
    .then(res => console.log(res.data)) //成功時
    .catch(err => console.log(err)); //失敗時

所感

参考にさせてもらった記事にもありましたが、色々調べててform.getHeaders()の箇所が直感的ではないのでちょっとハマりました。

参考

10
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
4