SuperAgentで画像送信の方法とTips


記事の内容

AxiosではなくSuperAgentの使うことになりました
その際に画像の送信でなど詰まったので方法やTipsをまとめます

SuperAgentとは

ブラウザやNode.jsで動作するajax APIです
基本的な使い方などは一番下に資料をまとめたので参考にしてください

画像などを送信したい時

使い方

import request from 'superagent';
request
    .post(url)
    .field('name', 'Image Name')
    .attach('image',file)

注意点

  1. .send()は使えないので.attach().field()を使いましょう
  2. Content-Typeは使わない(正しいtypeをセットしてくれます)

To send a file use .attach(name, [file], [options]). You can attach multiple files by calling .attach multiple times.

fieldでオブジェクトをまとめて渡す時

fieldは2通りの値の渡し方があります

field(name: string, val: MultipartValue): this;
field(fields: { [fieldName: string]: MultipartValue }): this;

const queryObj = {
    query1:'value1',
    query2:'value2',
    query3:'value3',
};

request
    .post(url)
    .field(queryObj)

sendでまとめて渡す時

const queryObj = {
    query1:'value1',
    query2:'value2',
    query3:'value3',
};

request
    .post(url)
    .send(stringfy(queryObj))

資料

公式ドキュメント
github
https://qiita.com/hashrock/items/3113690bb3de5bba639b