creating my polls page
This commit is contained in:
parent
28882e7038
commit
08b22b07c6
16 changed files with 266 additions and 24 deletions
50
SurveyFrontend/src/api/BaseApi.ts
Normal file
50
SurveyFrontend/src/api/BaseApi.ts
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
const BASE_URL = "https://survey.slavagm.ru/api";
|
||||
|
||||
interface RequestConfig {
|
||||
method: string;
|
||||
headers: Record<string, string>;
|
||||
body?: BodyInit | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Создаёт конфигурацию для fetch-запроса
|
||||
* @param method HTTP-метод (GET, POST, PUT, DELETE)
|
||||
* @param isFormData Флаг, указывающий, что отправляется FormData
|
||||
* @returns Конфигурация для fetch-запроса
|
||||
*/
|
||||
const createRequestConfig = (method: string, isFormData: boolean = false): RequestConfig => {
|
||||
const token = localStorage.getItem("accessToken");
|
||||
const config: RequestConfig = {
|
||||
method,
|
||||
headers: {},
|
||||
};
|
||||
|
||||
// Добавляем заголовок авторизации, если есть токен
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
// Добавляем Content-Type, если это не FormData
|
||||
if (!isFormData) {
|
||||
config.headers["Content-Type"] = "application/json";
|
||||
}
|
||||
|
||||
return config;
|
||||
};
|
||||
|
||||
/**
|
||||
* Обрабатывает ответ от сервера
|
||||
* @param response Ответ от fetch
|
||||
* @returns Распарсенные данные или ошибку
|
||||
*/
|
||||
const handleResponse = async (response: Response) => {
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.message || "Произошла ошибка");
|
||||
}
|
||||
|
||||
return data;
|
||||
};
|
||||
|
||||
export { BASE_URL, createRequestConfig, handleResponse };
|
||||
Loading…
Add table
Add a link
Reference in a new issue