要使用axios和代理(proxy)获取API数据,请按照以下步骤操作:
npm install axios
proxy.config.js
,并在其中设置代理服务器的相关信息:module.exports = {
target: 'https://api.example.com', // 目标API服务器地址
changeOrigin: true, // 是否改变源
pathRewrite: {
'^/api': '' // 重写路径:将/api替换为空字符串
}
};
index.js
)中,引入并使用上述代理配置文件:import axios from 'axios';
import proxyConfig from './proxy.config.js';
// 创建axios实例并设置代理
const api = axios.create({
baseURL: '/api',
proxy: proxyConfig
});
// 使用axios实例获取API数据
api.get('/your-endpoint').then(response => {
console.log(response.data);
}).catch(error => {
console.error(error);
});
领取专属 10元无门槛券
手把手带您无忧上云