Add new components for login and comment functionality
This commit is contained in:
37
composables/useDollarFetchRequest.ts
Normal file
37
composables/useDollarFetchRequest.ts
Normal file
@ -0,0 +1,37 @@
|
||||
import { isArray } from "~/utils/utils";
|
||||
|
||||
type FetchType = typeof $fetch;
|
||||
export type FetchOptions = Parameters<FetchType>[1];
|
||||
|
||||
export const useClientRequest = <T = unknown>(
|
||||
url: string,
|
||||
opts?: FetchOptions
|
||||
) => {
|
||||
const token = useCookie<string | undefined>("token");
|
||||
const runtimeConfig = useRuntimeConfig();
|
||||
|
||||
const defaultOptions: FetchOptions = {
|
||||
baseURL: runtimeConfig.public.apiBase,
|
||||
onRequest({ options }) {
|
||||
options.headers = options.headers || 'application/json';
|
||||
if (token.value) {
|
||||
// @ts-ignore
|
||||
options.headers["authorization"] = "Bearer " + token.value;
|
||||
}
|
||||
},
|
||||
onResponse({ response }) {
|
||||
if (+response.status === 200 && +response._data.code !== 200) {
|
||||
ElMessage.error(response._data.msg);
|
||||
}
|
||||
},
|
||||
onResponseError({ response }) {
|
||||
ElMessage.error(
|
||||
isArray(response._data.data.msg)
|
||||
? response._data.data.msg[0]
|
||||
: response._data.data.msg
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
return $fetch<T>(url, { ...defaultOptions, ...opts });
|
||||
};
|
||||
Reference in New Issue
Block a user