vite+Vue3技术栈项目- 解决跨域配置代理
vite+Vue3技术栈项目- 解决跨域配置代理1. 跨域问题引入2. 解决跨域编码:3. 更改后端请求:4. 编码测试OK1. 跨域问题引入我的前端项目启动,是 http://127.0.0.1:3000需要访问的后端接口是:http://localhost:9693/httphwm/getList如果直接请求,会出现跨域问题,如下:2. 解决跨域编码:在项目根目录下,创建文件 vite.con
·
vite+Vue3技术栈项目- 解决跨域配置代理
1. 跨域问题引入
我的前端项目启动,是 http://127.0.0.1:3000
需要访问的后端接口是:http://localhost:9693/httphwm/getList
如果直接请求,会出现跨域问题,如下:
2. 解决跨域编码:
-
在项目根目录下,创建文件
vite.config.ts
,配置文件如下:import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; // https://vitejs.dev/config/ export default defineConfig({ plugins: [vue()], server: { port: 3000, open: true, // 配置代理 proxy: { // 请求的路径前缀只要是 /testaxios 就会被拦截走这个代理 '/testaxios': { /** * 请求的目标资源再经过替换成 /httphwm/getList 后, * 会加上 http://127.0.0.1:9693 这个前缀, * 最后请求的URL为: http://127.0.0.1:9693/httphwm/getList */ target: 'http://127.0.0.1:9693', ws: true, changeOrigin: true, // 拦截到的请求路径 testaxios/httphwm/getList,/testaxios会被替换成空 rewrite: (path) => path.replace(/^\/testaxios/, ''), }, }, },
3. 更改后端请求:
只写资源路径即可: testaxios/httphwm/getList
<template>
<div>
<button @click.stop="clickHandler">点击测试axios请求</button>
</div>
</template>
<script lang="ts" setup>
import { get } from '../../../../common/request/index';
// 点击事件,请求接口
const clickHandler = async () => {
let res = await get('testaxios/httphwm/getList');
console.log('axios请求测试', res.data);
};
</script>
4. 编码测试OK
更多推荐
已为社区贡献4条内容
所有评论(0)