0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptでのリクエスト送信

0
Posted at

JavaScriptでのリクエスト送信

  • リクエストの設定(method, headers)
const options = {
    method: method,
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
    }
};
  • bodyの追加(method: POST, PUTの時)
  • JSON.stringifyで文字列にしないといけないらしい

理由: HTTP通信のルールで、サーバーに送るリクエストのBodyは「文字列」か「バイナリ」である必要があるため。JavaScriptのオブジェクトのままだと通信に乗せられない。そのため、JSON.stringify() を使ってオブジェクトを「JSON形式の文字列」に変換してから送信する。

options.body = JSON.stringify(body);
  • urlとoptionsでリクエスト送信
const response = await fetch(url, options);
  • 関数でまとめると便利

{}は何か: 引数をオブジェクトとして受け取る「分割代入」の仕組み。
メリット:
引数の順番を覚えなくていい(名前で指定するため)。
url=apiUrl のようにデフォルト値を設定しつつ、特定の引数だけを綺麗に省略できる。
呼び出し側のコードの可読性が上がる。

async function send_request({method, token, url=apiUrl, body = null}){

    const options = {
        method: method,
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        }
    };

    if (body) {
        options.body = JSON.stringify(body);
    }

    const response = await fetch(url, options);
    return response;
}
  • 呼び出し方(urlに変更がない時)
const response = await send_request({
    method: 'POST',
    token: token,
    body: task
});
  • 呼び出し方(urlに変更がある時)

注意:''ではなく、``を使う

const response = await send_request({
    method: 'DELETE',
    token: token,
    url: `${apiUrl}/${taskId}`
});
  • 呼び出し方(urlに変更(クエリ)がある時)
let requestUrl = apiUrl;
if (currentSort) {
    requestUrl = `${apiUrl}?sort=${currentSort}`;
}

const response = await send_request({
    method: 'GET',
    token: token,
    url: requestUrl
});
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?