Use Fetch API

This commit is contained in:
Pig Fang 2018-08-05 15:33:08 +08:00
parent a2e6315198
commit 5e4bc4b564
3 changed files with 56 additions and 5 deletions

View File

@ -1,3 +1,4 @@
import Vue from 'vue';
import axios from 'axios';
import { showAjaxError } from './notify';
@ -8,3 +9,48 @@ axios.interceptors.response.use(
response => response,
showAjaxError
);
const empty = Object.create(null);
const init = {
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
}
};
async function walkFetch(request) {
try {
const response = await fetch(request);
if (response.ok) {
return response.json();
} else {
showAjaxError(await response.text());
}
} catch (error) {
showAjaxError(error);
}
}
export async function get(url, params = empty) {
const qs = Object
.keys(params)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
.join('&');
return walkFetch(new Request(`${blessing.base_url}${url}${qs && '?' + qs}`, init));
}
export async function post(url, data = empty) {
return walkFetch(new Request(`${blessing.base_url}${url}`, {
body: JSON.stringify(data),
method: 'POST',
...init
}));
}
Vue.use(_Vue => {
_Vue.prototype.$http = {
get,
post,
};
});

View File

@ -20,16 +20,15 @@ export function showMsg(msg, type = 'info') {
/**
* Show modal if error occured when sending an ajax request.
*
* @param {{ response: import('axios').AxiosResponse }} response
* @param {TypeError | string} error
* @return {void}
*/
export function showAjaxError({ response }) {
if (!response.data) {
export function showAjaxError(error) {
if (!error) {
return console.warn('Empty Ajax response body.');
}
const message = typeof response.data === 'object' ? response.data.message : response.data;
const message = typeof error === 'string' ? error : error.message;
showModal(message.replace(/\n/g, '<br />'), trans('general.fatalError'), 'danger');
}

View File

@ -17,5 +17,11 @@ declare global {
declare module 'vue/types/vue' {
interface Vue {
$t(key: string, parameters?: object): string
$http: {
get(url: string, params?: object)
post(url: string, data?: object)
}
}
}