2025-11-17 19:07:04 +08:00
|
|
|
|
import axios,{type AxiosInstance,AxiosError} from 'axios';
|
|
|
|
|
|
import { type WeatherData } from '@/store/weatherStore';
|
|
|
|
|
|
|
2025-11-17 19:13:23 +08:00
|
|
|
|
|
2025-11-17 19:07:04 +08:00
|
|
|
|
const API_KEY = '0c4679ac2decfe6a756aa09e61f42dc1';
|
|
|
|
|
|
const BASE_URL = 'http://api.weatherstack.com';
|
|
|
|
|
|
|
|
|
|
|
|
const apiClient: AxiosInstance = axios.create({
|
|
|
|
|
|
baseURL: BASE_URL,
|
|
|
|
|
|
timeout: 10000,
|
|
|
|
|
|
headers: {
|
|
|
|
|
|
'Content-Type': 'application/json'
|
|
|
|
|
|
}
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
apiClient.interceptors.request.use(
|
|
|
|
|
|
(config) => {
|
|
|
|
|
|
config.params = {...config.params, access_key: API_KEY };
|
|
|
|
|
|
if (process.env.NODE_ENV === 'development'){
|
|
|
|
|
|
console.log('API Request:', config.method ?.toUpperCase(), config.url);
|
|
|
|
|
|
}
|
|
|
|
|
|
return config;
|
|
|
|
|
|
},
|
|
|
|
|
|
(error) => {
|
|
|
|
|
|
console.error('Request Error:' ,error);
|
|
|
|
|
|
return Promise.reject(error);
|
|
|
|
|
|
}
|
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
|
|
apiClient.interceptors.response.use(
|
|
|
|
|
|
(response) => {
|
|
|
|
|
|
if (response.data && response.data.error){
|
|
|
|
|
|
const error = response.data.error;
|
|
|
|
|
|
console.error('API Error:', error);
|
|
|
|
|
|
throw new Error(error.info || '请求失效');
|
|
|
|
|
|
}
|
|
|
|
|
|
if (process.env.NODE_ENV === 'development'){
|
|
|
|
|
|
console.log('API Response:', response.config.url,response.data);
|
|
|
|
|
|
}
|
|
|
|
|
|
return response;
|
|
|
|
|
|
},
|
|
|
|
|
|
(error :AxiosError)=>{
|
2025-11-17 19:13:23 +08:00
|
|
|
|
|
|
|
|
|
|
console.error('Response Error:',error.message);
|
|
|
|
|
|
if (error.response) {
|
|
|
|
|
|
const status = error.response.status;
|
|
|
|
|
|
if (status === 404) {
|
|
|
|
|
|
throw new Error('未找到该城市的天气信息');
|
|
|
|
|
|
} else if (status === 401) {
|
|
|
|
|
|
throw new Error('API认证失败,请检查API');
|
|
|
|
|
|
} else if (status === 403) {
|
|
|
|
|
|
throw new Error('请检查API密钥是否正确');
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
else if (error.request) {
|
|
|
|
|
|
throw new Error('网络连接失败');
|
|
|
|
|
|
}
|
|
|
|
|
|
else {
|
|
|
|
|
|
return (('配置错误'))
|
2025-11-17 19:07:04 +08:00
|
|
|
|
}
|
2025-11-17 19:13:23 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
|
|
export class WeatherApi {
|
|
|
|
|
|
static async getCurrentWeather(city: string): Promise<WeatherData> {
|
|
|
|
|
|
try {
|
|
|
|
|
|
const response = await apiClient.get<WeatherData>('/current',{
|
|
|
|
|
|
params:{query :city} ,
|
|
|
|
|
|
});
|
|
|
|
|
|
return response.data;
|
|
|
|
|
|
}catch (error){
|
|
|
|
|
|
throw error;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2025-11-17 19:07:04 +08:00
|
|
|
|
|
2025-11-17 19:13:23 +08:00
|
|
|
|
}
|
|
|
|
|
|
export default WeatherApi;
|