1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

axiosライブラリを使ったHTTP通信

Posted at

axios とは

HTTP通信を簡単に行うことができるJavascriptライブラリ

GET通信を行う

index.js

// GET通信

axios.get('http://localhost:3000/users')

    // thenで成功した場合の処理をかける
    .then(response => {
        console.log('status:', response.status); // 200
        console.log('body:', response.data);     // response body.

    // catchでエラー時の挙動を定義する
    }).catch(err => {
        console.log('err:', err);
    });

また、以下のようにaxiosにconfigオブジェクトを渡す形でも、GET通信を行うことができます。

index.js

// configオブジェクトを使ったGET通信の例
axios({
    method : 'GET',
    url    : 'http://localhost:3000/users'
}).then(response => console.log(response.status));

POST通信

POST通信を行う場合には、axios.post関数を用います。

index.js

// POST通信
// POSTデータは、axios.postの第2引数で渡します.
const data = { firstName : 'Yohei', lastName : 'Munesada' };
axios.post('http://localhost:3000/users', data).then(response => {
    console.log('body:', response.data);  // Yohei Munesada
});

// または、configオブジェクトを使う場合
axios({
    method : 'POST',
    url    : 'http://localhost:3000/users',
    data   : { firstName : 'Yohei', lastName : 'Munesada' }
}).then(response => console.log(response.status));

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?