You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
bloggingplatform/Frontend/api/userApi.js

74 lines
1.9 KiB

import axios from 'axios';
// 使用 import.meta.env 访问环境变量
const apiBaseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api';
// 创建一个 Axios 实例,设置默认配置
const apiClient = axios.create({
baseURL: apiBaseURL,
withCredentials: true, // 确保携带凭证
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
});
export const registerUser = async (user) => {
try {
const response = await apiClient.post('/users/register', user);
return response.data;
} catch (error) {
throw new Error(error.response?.data || error.message);
}
};
export const loginUser = async (loginAccount, password) => {
try {
const params = new URLSearchParams({
loginAccount,
password
});
const response = await apiClient.post('/users/login', params);
return response.data;
} catch (error) {
console.error('Login failed:', error.response?.data || error.message);
throw new Error('Login failed');
}
};
export const getCurrentUser = async () => {
try {
const response = await apiClient.get('/users/me');
return response.data;
} catch (error) {
throw new Error(error.response?.data || error.message);
}
};
export const logoutUser = async () => {
try {
const response = await apiClient.post('/users/logout');
return response.data;
} catch (error) {
throw new Error(error.response?.data || error.message);
}
};
export const updateUser = async (updatedUser) => {
try {
const response = await apiClient.put('/users/me', updatedUser);
return response.data;
} catch (error) {
throw new Error(error.response?.data || error.message);
}
};
export const resetPassword = async (currentPassword, newPassword) => {
try {
const response = await apiClient.post('/users/me/reset-password', { currentPassword, newPassword });
return response.data;
} catch (error) {
throw new Error(error.response?.data || error.message);
}
};