– axiosは、HTTP通信を簡単に行うことができるJavascriptライブラリ
https://github.com/axios/axios
– 主にJsonの取得に利用される
### Features
– Make XMLHttpRequests from the browser
– Make http requests from node.js
– Supports the Promise API
– Intercept request and response
– Transform request and response data
– Cancel requests
– Automatic transforms for JSON data
– Client side support for protecting against XSRF
## サンプル
### npm install
$ npm install axios –save
### index.js
– axios.get(‘${url}’), axios.post(‘${url}’)と実装する
– get, post以外にも、request, delete, head, options, put, patch, getUriなどがある
var express = require('express');
var router = express.Router();
// axiosのインスタンス生成
const axiosBase = require('axios');
const axios = axiosBase.create({
baseURL = '192.168.33.10:8000',
headers: {
'Content-Type' : 'application/json',
'X-Requested-With': 'XMLHttpRequest'
},
responseType: 'json'
});
router.get('/', function(req, res, next){
axios.get('/title')
.then(function(response){
res.render('index', response.data);
})
.catch(function(error){
console.log('Error!! occurred in Backend.')
});
});
module.exports = router;
### res, err, finally
<script>
axios.get(${url})
.then(res => console.log(res.data))
.catch(err => console.error(err))
.finally(res => console.log('finally'))
</script>
XMLHttpRequestを生成せずに処理できるので、確かに使い勝手良さそうです。