vue3解决跨域问题

glorystar / 2024-08-22 / 原文

 

vue3登录提示错误

 解决方法
1,修改根目录下 vite.config.ts 文件 

  修改 host、proxy、target,修改后文件如下(红色为修改),具体内容根据后台实际修改

		server: {
			host: 'localhost',
			port: env.VITE_PORT as unknown as number,
			open: JSON.parse(env.VITE_OPEN),
			hmr: true,
			proxy: {
				'/api': {
					target: 'http://localhost:5132/',
					ws: true,
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/gitee/, ''),
				},
			},
		},

2,修改 axios请求的文件,如request.ts。

  将 axios 实例示例,将baseURL的值与上一步的proxy的值相同

const service: AxiosInstance = axios.create({
	baseURL: '/api',
	timeout: 50000
});

3,修改相应的api函数。  

本文参考:解决Vu3 axios 跨域问题 Vue CORS错误_vue cors error-CSDN博客