我在本地计算机上运行两个 Flask 应用程序。
1) 我的测试客户端网站(端口 5001)
2) 我的 API(端口 5000)
如果我在浏览器中输入 127.0.0.1:5000/search/
,我会得到以下内容:
Test Hello World
如果我在浏览器中输入 127.0.0.1:5001
,我会得到一个包含以下 HTML 代码的普通网页(这一切看起来都不错):
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo">TEST</p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "127.0.0.1:5000/search/", true);
xhttp.send();
}
</script>
</body>
</html>
正如您所看到的,HTTP 请求被发送到 127.0.0.1:5000/search/
,该请求已在浏览器中进行了测试并正常工作,并且应该返回 Test Hello World
,但是不幸的是什么也没发生。
基本上,我单击“请求数据”按钮(见上文),但完全没有任何反应。
有什么想法吗?我已经在这个问题上坚持了好几个小时了。
最佳答案
For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest follows the same-origin policy. So, a web application using XMLHttpRequest could only make HTTP requests to its own domain. To improve web applications, developers asked browser vendors to allow XMLHttpRequest to make cross-domain requests.
这些资源可能会有所帮助;
HTTP access control (CORS)
Using CORS
关于javascript - HTTP 从本地服务器请求数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37549758/