Vite 解决跨域问题:使用代理功能 | DOMException: Blocked a frame with origin "http://localhost:5173" from accessing a cross-origin frame.
Vite 通过使用开发服务器的代理功能来解决跨域问题。在 Vite 的配置文件 vite.config.js 中,可以配置代理规则。
下面是一个示例的 vite.config.js 文件,配置了一个简单的代理规则来解决跨域问题:
module.exports = {
server: {
proxy: {
'/api': {
target: 'http://example.com', // 修改为实际后端接口的地址
changeOrigin: true,
rewrite: (path) => path.replace(/^/api/, '')
}
}
}
}
上述配置中,将所有以 /api 开头的请求代理到了 http://example.com,并将请求路径中的 /api 部分移除。你可以根据实际情况修改 target 和 rewrite 的配置。
配置完成后,重启 Vite 开发服务器,就可以通过 http://localhost:5173/api 来访问后端接口,避免了跨域问题。
注意:在生产环境下,由于 Vite 不会处理服务器端的代码,所以跨域问题应该在服务器端进行配置,而不是依赖 Vite 的代理功能。
原文地址: https://www.cveoy.top/t/topic/qugc 著作权归作者所有。请勿转载和采集!