由于我不知道的原因,我不能在我的本地服务器中使用 xmlhttprequest,这是在 Node js 和 express 中创建的。让我演示给你看... 这是 Node JS 中的服务器:
var
express = require('express'),
app = express.createServer();
app.get('/count', function(req, res) {
res.type('text/plain');
res.write('Hello!')
res.end();
});
app.listen(4003);
它运行得很好!当我访问 localhost:4003/count 时,我看到“你好!”。
现在服务器是O.K,让我们检查一下html页面:
<script>
var xmlhttp = new XMLHttpRequest();
var resp = ""
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200){
resp = xmlhttp.responseText;
}
}
var cam = "localhost:4003/count"
function show(){
xmlhttp.open("GET",cam, true);
xmlhttp.send();
alert(resp);
}
</script>
<center><h1><div style="color:#339966"> <input type="button" value="Return of /count" onclick="javascript:show()"> </div> </h1>
所以,它就是行不通 =[,我已经尝试过:
- 将
localhost:4003/count
更改为变量cam
的值,对于http://localhost:4003/count
,127.0.0.1:4003/计数
。 - 在 Firefox、Safari 和 Chrome 中打开。
- 当我尝试查看带有
alert()
的xmlhttp.status
时,它显示“0
”。 (但该页面在任何浏览器中都能正常打开)
最佳答案
随着时间问题 Morgan already covered ...
当在 URL 中包含一个主机时,它需要加上前缀
//
。var cam = "//localhost:4003/count";
否则,它将被视为以
localhost:4003
作为目录名称的相对路径。您还必须处理 Same-Origin Policy使用 Ajax 时。
因此,如果您尝试对页面使用
file://
,这通常不会很好地工作。FILE
协议(protocol)没有来源,因此无法通过 SOP,导致出现类似于以下的错误:Origin null is not allowed by Access-Control-Allow-Origin.
最简单的解决方案是同时从应用程序提供页面。
您可以使用
static()
middleware .// `GET /` will serve `./public/index.html` app.use(express.static(__dirname + '/public'));
或者使用另一条路线 sends the file本身。
app.get('/', function (req, res) { res.sendfile(__dirname + '/public/index.html'); });
然后,从以下位置访问页面:
http://localhost:4003/
此外,由于页面和
count
现在从同一来源提供,URL 可以简单地从根相对:var cam = "/count";
关于javascript - 带有 express Node js 服务器的 XMLhttpRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18414019/