46 lines
1.2 KiB
TypeScript
46 lines
1.2 KiB
TypeScript
|
|
import axios,{type AxiosInstance,AxiosError} from 'axios';
|
||
|
|
import { type WeatherData } from '@/store/weatherStore';
|
||
|
|
|
||
|
|
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)=>{
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
);
|