Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8882

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

$
0
0

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

環境

Node.js v13.2.0

準備

mkdir myapp
cd myapp
npm init -y
npm i axios

こんな感じでaxiosだけ追加インストールです。

コード

post.js
'use strict';constfs=require('fs');constFormData=require('form-data');constaxios=require('axios');consturl=`https://hogehoge.com/hogehoge`;//ポスト先のエンドポイントURLconstimagePath=`./public/image.png`;//画像のパスconstfile=fs.createReadStream(imagePath);constform=newFormData();form.append('image',file);constconfig={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()の箇所が直感的ではないのでちょっとハマりました。

あとform-dataって標準モジュールになってるんですね(?) とくにnpm installしてないのに使えました。

参考


Viewing all articles
Browse latest Browse all 8882

Trending Articles