Help us understand the problem. What is going on with this article?

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

naoya7076
Web系エンジニアです
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした