axios串接API
6 min readOct 6, 2021
使用axios串接API快速範例
註冊功能說明
<!--file:axiosEx1.html --><!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8">
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src=”https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<! — some function code →
<! — your own js , suggget loading after body →
<script src=”axiosEx1.js”></script>
</body>
</html>
下圖重點在axios.post的用法
<!--file:axiosEx1.js-->// test account
let obj = {
email: ‘jameskrauser123456@gmail.com’,
password: ‘12345678’
} axios.post(‘https://hexschool-tutorial.herokuapp.com/api/signup', obj
)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
接下來你可以用看到以下response.data.message回傳帳號註冊成功
上方例子為把帳號密碼寫在CODE中,以下為用input方式,及加上另一個登入功能
<!--File: axiosEx2.html --><!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8">
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src=”https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Account:
<input type=”text” class=”account”>
<br>
Pwd:
<input type=”text” class=”pwd”>
<br>
<input type=”button” value=”send” class=”send”>
<script src=”axiosEx2.js”></script>
</body>
</html>
上方.html要注意class account , pwd and send因為下方的axiosEx2.js中是透過這幾個class去取值及addEventListener的
<!--File: axiosEx2.js -->const account = document.querySelector(‘.account’);
const pwd = document.querySelector(‘.pwd’);
const send = document.querySelector(‘.send’);send.addEventListener( ‘click’ , function(e){
// console.log(‘this is clicked.’);
callSignUp();
})function callSignUp() {
if( account.value == “” || pwd.value == “” ) {
alert(“請輸入資訊”);
return;
}
let obj= {};
obj.email = account.value;
obj.password = pwd.value;console.log(obj);
axios.post(‘https://hexschool-tutorial.herokuapp.com/api/signup', obj
)
.then(function (response) {
// console.log(response.data.message);
// alert( response.data.message );
if( response.data.message == “帳號註冊成功” ){
alert( obj.email + “ 你成功註冊了喔”);
}else{
alert(obj.email + “ 你註冊失敗了喔”);
}
account.value = “”;
pwd.value = “”;})
.catch(function (error) {
console.log(error);
});
}
以上只是快速入門例子
細部axios用法再看
https://github.com/axios/axios
https://github.com/hexschool/nodejs_ajax_tutorial
codePen
axios_ex1
axios_ex2_form