Vue3本身并不能解决跨域问题,但是可以通过配置代理服务器来解决跨域问题。以下是实现步骤:
1. 在Vue3项目的根目录下创建vue.config.js文件,如果已经存在则直接打开。
2. 在vue.config.js文件中添加以下代码:
“`javascript
module.exports = {
devServer: {
proxy: {
‘/api’: {
target: ‘http://localhost:3000’, // 代理服务器地址
changeOrigin: true,
pathRewrite: {
‘^/api’: ” // 将/api替换为空字符串
}
}
}
}
}
“`
3. 上述代码中,我们配置了一个代理服务器,将所有以/api开头的请求都代理到http://localhost:3000地址上。changeOrigin参数表示是否改变请求头中的origin字段,pathRewrite参数表示将请求路径中的/api替换为空字符串。
4. 在Vue3项目中发起请求时,将请求路径改为以/api开头即可,例如:
“`javascript
axios.get(‘/api/users’)
.then(response => {
console.log(response.data)
})
.catch(error => {
console.log(error)
})
“`
5. 运行Vue3项目,代理服务器会将请求转发到http://localhost:3000地址上,从而解决跨域问题。