每日進度2 Flashcards
1
Q
fetch的回傳值
A
- a ReadableStream object
- 所以需要==根據不同資料類型==使用對應方法,才能正確取得資料物件 (i.e. .json()..etc.)
- why fetch? => JQ太大
- fetch不是ajax的進一步封裝!而是原生JS!
- ==沒有使用==XMLHttpRequest Object
2
Q
fetch的缺點
A
- 對400,500都當做成功的請求,需要另外做處理
- 預設是==沒有==帶cookie
- ==不支援==timeout handle
- 較早的瀏覽器並不支援
- fetch是比較底層的api,所以需要手動拼接參數
(i. e. 將參數拼接成’name=test’的格式)
// 6. 不支援監測請求的進度
3
Q
axios的優點
A
- 支援Promise
- 可以在nodejs中使用
3. 支援 ==CSRF (cross-site request forgery) 跨域偽造== // 模擬、偽造用戶請求、6個步驟
- 支援==並發請求 (parallel)== // axios.all
4
Q
axios中的並發請求 (哪2個?) // parallel
A
function getUserAccount () { return axios.get('/user/12345'); }
function getUserPermissions () { return axios.get('/user/12345/permissions'); }
axios
.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (account, permissions) {
// do sth.
}));
5
Q
如何管理ajax call
A
- 方便一次性的改變api domain
- axios.create
6
Q
使用axios.create來管理ajax call的範例
A
https://medium.com/i-am-mike/%E4%BD%BF%E7%94%A8axios%E6%99%82%E4%BD%A0%E7%9A%84api%E9%83%BD%E6%80%8E%E9%BA%BC%E7%AE%A1%E7%90%86-557d88365619
==================
import axios from ‘axios’;
// User相關的 api const userRequest = axios.create({ baseURL: 'https://api/user/' }); // 文章相關的 api const articleRequest = axios.create({ baseURL: 'https://api/article/' }); // 搜尋相關的 api const searchRequest = axios.create({ baseURL: 'https://api/search/' });
// User 相關的 api export const apiUserLogin = data => userRequest.post('/signIn', data); export const apiUserLogout = data => userRequest.post('/signOut', data); export const apiUserSignUp = data => userRequest.post('/signUp', data);
// 文章相關的 api export const apiArticleItem = () => articleRequest.get('/ArticleItem'); export const apiArticleMsg = data => articleRequest.post('/ArticleMsg', data); export const apiArticleLink = data => articleRequest.post('/ArticleLink', data);
// 搜尋相關的 api export const apiSearch = data => searchRequest.get(`/Search?searchdata=${data}`); export const apiSearchType = () => searchRequest.get(`/SearchType`);
=============
??????????why?????try it
import { apiArticleItem, apiSearchType } from “api.js”;
async function getData() { try { const item = await apiArticleItem(); const type = await apiSearchType(); retrun {item, type} } catch (err) { console.error(err); } }
console.log(getData());
7
Q
axios.get
A
- params in GET
- axios.get(‘/user’, {
params: { id: 12345 },
header: { token: ‘abc’ },
}).then((response = {}) => {
console.log(response);
}).catch((error = {}) => {
console.log(error);
});
8
Q
axios.post
A
- NO params in POST
- axios.post('/user', { firstName: 'alvin', lastName: 'yen', }).then((response = {}) => { console.log(response); }).catch((error = {}) => { console.log(error); });