在axios里面先创建实例
import axios from 'axios'
const requests = axios.create({
baseURL: '/api',
timeout: 5000
})
export default requests;
然后配置,拦截api开头的请求,把它代理到远程服务器,再把api干掉
server: {
proxy: {
'/api': {
target: 'http://localhost:3005',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
},
}
},
嫌麻烦可以直接配置远程服务器,创建.env.development
封装axios这么写
import axios from 'axios'
const requests = axios.create({
baseURL: import.meta.env.VITE_API_URL,//从环境中获取远程服务器地址
timeout: 5000
})
export default requests;
然后直接请求就行
requests({
url: '/products',
}).then(res => {
state.tableData = res.data
})
两种方法都可请求数据