Cloudflare Pages 部署 Vue 项目跨域交互解决方案
若使用 Cloudflare Pages 部署 Vue 项目,可以在项目根目录下添加一个 'vue.config.js' 文件,然后在该文件中配置反向代理来实现和后端的跨域交互。
以下是一个简单的 'vue.config.js' 配置示例,将请求转发到后端 'http://localhost:3000':
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
在 Vue 组件中,可以使用 'axios' 或 'fetch' 等工具发送请求到反向代理的接口,如:
axios.get('/api/users')
.then(response => {
console.log(response.data)
})
.catch(error => {
console.log(error)
})
注意,由于 Cloudflare Pages 会自动配置 HTTPS,因此在请求时需要使用 HTTPS 协议,否则可能会遇到安全限制而无法发送请求。
原文地址: https://www.cveoy.top/t/topic/ovUY 著作权归作者所有。请勿转载和采集!