CORS问题通常是由于浏览器的安全机制防止跨域请求导致的。要解决这个问题,一种常见的方法是使用代理服务器,使所有请求通过代理服务器。以下是一个示例代码来解决Axios的GET调用遇到CORS问题:
axios.get('https://api.example.com/data')
.then(response => {
// handle success
console.log(response.data);
})
.catch(error => {
// handle error
console.log(error);
});
// 声明代理服务
const proxyUrl = 'https://cors-anywhere.herokuapp.com/';
// 添加headers参数
axios.get(proxyUrl + 'https://api.example.com/data', {
headers: {
'x-requested-with': 'XMLHttpRequest'
}
})
.then(response => {
// handle success
console.log(response.data);
})
.catch(error => {
// handle error
console.log(error);
});
在代码中,我们首先声明了一个代理服务,并添加了headers参数。然后,在Axios的GET调用中,使用代理服务器url加上目标url,就可以解决CORS问题。