資源使用
API 連結與欲呈現的資料格式
1 2 3 4 5
| const url = "https://hexschool-tutorial.herokuapp.com/api/signup"; const user = { email: "123e@gmail.com", password: "123456", };
|
XHR 傳統寫法
1 2 3 4 5 6
| xhr = new XMLHttpRequest(); xhr.open("post", url, true); xhr.setRequestHeader("Content-type", "application/json"); xhr.send(JSON.stringify(user)); response = JSON.parse(xhr.response); report.innerHTML = response.message;
|
ES6:Fetch
1 2 3 4 5 6 7
| fetch(url, user) .then((res) => { return res.json(); }) .then((jsonData) => { console.log(jsonData); });
|
axios
1 2 3
| axios.post(url, user).then((res) => { report.innerHTML = res.data.message; });
|
CodePen:https://codepen.io/hnzxewqw/pen/eYZJBYa