手把手教你用vite搭建vue3.0项目(三):跨域代理
1. 安装axios
值得一提的是,这里不用再加@next了,直接用就好。
yarn add axios
2. 请求接口
为了展示,我直接在Home.vue中使用,对于axios大家可以自行封装。
和之前vue2项目没有太大区别, 最多就是把比如api.js改成api.ts。
Home.vue
<script lang="ts"> import { defineComponent, onMounted } from "vue"; import axios from "axios"; export default defineComponent({ name: "Home", components: {}, setup() { onMounted(()=>{ axios.get(`http://api.example.com/search?keywords=vue3`).then(res=>{ console.log(res) }) }) }, }); </script>
跨域也是在情理之中,所以来到下一步,配置跨域代理。
3. 跨域代理
找到vite.config.ts,新建server部分代码
import { defineConfig } from vite import vue from @vitejs/plugin-vue // https://vitejs.dev/config/ export default defineConfig({ plugins: [vue()], server: { host: 0.0.0.0, port: 8080, proxy: { /api: { target: http://api.example.com, //实际请求地址 changeOrigin: true, rewrite: (path) => path.replace(/^/api/, ) }, } } })
将原来项目中的请求地址改成以/api开头的,如:
axios.get(`/api/search?keywords=vue3`).then(res=>{ console.log(res) })
使用【本机pi】:8080重新启动项目,可以看到跨域问题解决了。
注意本来启动项目是使用localhost:3000,因为这里vite.config.ts做出了修改,所以换成了【本机ip】:8080
有人就会问了,怎么写法和平时看到的博客不一样呢。
其实,还不是因为vite文档更新了。
所以还是以文档为准: