LoginSignup
3
0

More than 3 years have passed since last update.

SuperAgentで画像送信の方法とTips

Last updated at Posted at 2019-12-26

記事の内容

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

3
0
1

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
3
0