前言
我们在开发网页的时候一定会处理到 RESTful API ,当网页上需要接多台server API时,如果不管理 API就会变得混乱,
在这边我选用 axios来作为我处理非同步的工具
基本语法
axios 回传的物件是 Promise (fulfilled 状态),所以我们可以使用.then 及.catch 处理成功和失败的结果。
axios(url [,config])
const x = axios('url')
x.then((response)=>console.log(x))
Request method请求方法
下列图示为发送 request 后所得到的回传结果:
config:发送请求时的配置data:实际的响应主体,即回传的资料内容headers:服务器发回标头request:XMLHttpRequest 物件status:HTTP 状态码statusText:以文字讯息形式返回的 HTTP 状态
//axios 方法
//GET请求
axios.get('url')
.then( (response) => console.log(response))
.catch( (error) => console.log(error))
//POST请求
axios.post('url',{
email: 'javascriptBasics@gmail.com',
password: '1234'
})
.then( (response) => console.log(response))
.catch( (error) => console.log(error))
范例如下
axios.get('/user', {
params: { // 如果有参数才需要加param,没有的话可以不用写
ID: 12345
}
})
.then(function (response) { // 成功后要做的事
return response.data;
console.log(response);
})
.catch(function (error) { // 失败后要做的事
return Promise.reject(error);
console.log(error);
})
.then(function () { // 不管成功或失败都要做的事
// always executed
});
//另外也支援 async/await 语法
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
return response.data;
} catch (error) {
return Promise.reject(error);
}
}
// 封裝其他请求方法如 POST、PUT...
export { GET, POST, PUT };
//post 通常用来传递比较重要的参数跟资料,**跟 get 差别在于 post 不会把参数显示在 URL 中,像是登入的帐密就要用 post 才不会被看光光**
axios.post('/user', { // 参数要用大括号包起来
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) { // 成功后要做的事
console.log(response);
})
.catch(function (error) { // 失败后要做的事
console.log(error);
});
Interceptors 拦截器
axios 拦截器可以在发送 requests 或回传 responses而进入 then 或 catch 之前,设定需要提前处理的事项。例如会员登入系统需要验证会员身份,同时登入 API 在设定规格时也会指定请求需在 header 带上 Token(加密),所以当会员点击登入按钮、触发登入 API 时,赶在发送 requests 到后端之前,先判断该名会员是否有 Token 资料,若有则将 Token 带入 header 跟着 request 一起传给后端,这样一来后端就能从 request header 取得 Token 进行会员身份的验证。
// Add a request interceptor
bookAPI.interceptors.request.use(
function (config) {
// Do something before request is sent
// 会员系统需验证身份时
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
},
function (error) {
return Promise.reject(error);
}
);
// Add a response interceptor
bookAPI.interceptors.response.use(
function (response) {
// 任何 HTTP status code 为 2xx 开头时触发此函式
return response;
},
function (error) {
// 任何 HTTP status code 非 2xx 开头时触发此函式
return Promise.reject(error.response);
});
参考资料
小声说
如果喜欢请给个赞或星星喔,谢谢~
这篇只是必须要掌握的基础知识喔,
axios在稍微复杂的项目中都必须进行封装,便于api的管理和维护,请把这篇也学起来~