mirror of
https://github.com/bs-community/blessing-skin-server.git
synced 2025-01-06 13:34:50 +08:00
Use Fetch API
This commit is contained in:
parent
a2e6315198
commit
5e4bc4b564
@ -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,
|
||||
};
|
||||
});
|
||||
|
@ -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');
|
||||
}
|
||||
|
||||
|
6
resources/assets/src/shims.d.ts
vendored
6
resources/assets/src/shims.d.ts
vendored
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user