解决跨域资源共享 (CORS) 错误:修改代码示例
要解决跨域资源共享 (CORS) 错误,你可以在发送请求前添加一些头部信息。以下是一种可能的方法:
const url = 'http://users.qzone.qq.com/fcg-bin/cgi_get_portrait.fcg?uins=3082422037';
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*'); // 添加这一行
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
// 处理响应
}
};
xhr.send();
在上面的代码中,我们添加了xhr.setRequestHeader('Access-Control-Allow-Origin', '*');这一行来设置允许跨域请求。这将允许来自任何源的请求通过。请注意,这只是在前端请求中设置CORS头,如果服务器没有正确配置CORS,仍然可能会出现错误。
原文地址: https://www.cveoy.top/t/topic/qqyS 著作权归作者所有。请勿转载和采集!