javascript - 带有 express Node js 服务器的 XMLhttpRequest

标签 javascript node.js express

由于我不知道的原因,我不能在我的本地服务器中使用 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/count127.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/

相关文章:

node.js - Cassandra 的类型 ORM

node.js - 如何在 Node.js 中管理多个网络客户端

javascript - MongoDB Mongoose 使用数组保存或更新

html - 使用 Jade 呈现的 HTML 值中的额外空格

node.js - 将 Nodejs 与 IIS 结合使用,以使用 Express 实现 REST 服务

node.js - 如何在 Express 中布置 Handlebars 部分

javascript - Uncaught ReferenceError : makePopunder is not defined

javascript - 无法读取未定义的属性 'ref'

javascript - 如何最好地从原生 JavaScript 对象继承? (尤其是字符串)

javascript - Electron - openShowDialog 未定义