gpt4 book ai didi

javascript - 从源 'file:///sample.txt' 访问位于 'null' 的 XMLHttpRequest 被 CORS 策略 : CORS are only supported for protocol schemes 阻止

转载 作者:行者123 更新时间:2023-12-03 20:59:53 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





"Cross origin requests are only supported for HTTP." error when loading a local file

(29 个回答)


2年前关闭。




我是 AJAX 的新手,目前正在学习它的基础知识。在我点击提交按钮的 html 文件中,我只是想记录一个文本文件的文本,该文本文件位于 html 文件本身的同一目录中。但相反,我得到了一个错误

从源“null”访问“file:///D:/Front_end_files/AJAX/sample.txt”的 XMLHttpRequest 已被 CORS 策略阻止:跨源请求仅支持协议(protocol)方案:http、data、chrome、chrome -扩展,https。

这是我的Ajax-1.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Ajax-1 Text file</title>
</head>
<body>
<button id="btn">Click Me</button>

<script>
document.getElementById('btn').addEventListener('click',loadtext);

function loadtext(){

let xhr = new XMLHttpRequest();
console.log(xhr);

xhr.open('GET', 'sample.txt', true);

xhr.onload = function(){
if(this.status == 200){
console.log(this.responseText);
}
};

xhr.send();
}
</script>
</body>
</html>

有人能告诉我我在这里做错了什么还是 chrome 和 firefox 的新功能?

最佳答案

不鼓励这种行为,因为它在您的计算机中提供了安全漏洞,我们不希望能够对我们的文件执行 AJAX 请求,这会将我们的本地系统暴露给网络。

正如他们之前所说,CORS doesn't support local file:// access所以你必须找到一种方法,一个简单的方法是使用 python 提供一个简单的 HTTPServer 并在那里提供文件,例如:

python -m SimpleHTTPServer 8080

这会将您当前的工作目录作为小型网络服务器提供服务。

关于javascript - 从源 'file:///sample.txt' 访问位于 'null' 的 XMLHttpRequest 被 CORS 策略 : CORS are only supported for protocol schemes 阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58879729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com