【问题标题】:Getting basic node.js server and a client to work让基本的 node.js 服务器和客户端工作
【发布时间】:2014-02-23 12:59:53
【问题描述】:

尝试在我的 PC 上实现最简单的服务器客户端。

argv 部分是因为我在 VS 中调试它并且它作为应用程序启动。它作为一个独立的应用程序工作,我想让它成为一个服务器。如果我输入

http://localhost:8080/ 

在浏览器中,我可以在 node.exe 窗口中看到服务器正常运行。但是当我用脚本运行 html 时,什么也没有发生(我没有得到响应,虽然也没有错误,服务器也没有收到请求)

如果有人可以提供帮助,我将不胜感激。

客户:

<html>
<body>

<script type = "text/javascript">
<!-- 
    //Browser Support Code
    function ajaxFunction() {
        var ajaxRequest;  // The variable that makes Ajax possible!

        try {
            // Opera 8.0+, Firefox, Safari
            ajaxRequest = new XMLHttpRequest();
        } catch (e) {
            // Internet Explorer Browsers
            try {
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    // Something went wrong
                    alert("Your browser broke!");
                    return false;
            }   
            }
        }
        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function () {
            if (ajaxRequest.readyState == 4) {
                document.myForm.response.value = ajaxRequest.responseText;
            }
        }
        ajaxRequest.open("GET", "http://localhost:8080", true);
        ajaxRequest.send(null);
    }

    //-->
</script>



<form name='myForm'>
<button onclick="ajaxFunction()">request</button> <br />
<input type='text' name='response' />
</form>
</body>
</html>

服务器:

var fs       = require("fs"),
    my_http = require("http"),
    sys = require("sys");

my_http.createServer(function(request,response){  


    fs.readFile(process.argv[2], 'utf8', function(err, data) {
    if (err) {
        console.log("FILE READ ERROR: ", err);
        process.exit();
     }
    response.writeHeader(200, {"Content-Type": "text/plain"});  
    response.write("message");
    response.end();
});




}).listen(8080);  
sys.puts("Server Running on 8080");

编辑:

嗯,你可以说我取得了一些进展,但我不喜欢不知道问题出在哪里。我在 VS 中创建了一个新的 TypeScript 项目,并将我的 ajaxFunction 和按钮\文本框放入初始 html 文件中。现在服务器确实收到了请求,但它似乎没有调用回调函数 onreadystatechange。

新的客户端代码:

default.htm:

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>TypeScript HTML App</title>
    <link rel="stylesheet" href="app.css" type="text/css" />
    <script src="app.js"></script>
</head>
<body>
    <h1>TypeScript HTML App</h1>

    <div id="content"></div>
    <button onclick="ajaxFunction()">request</button> <br />
    <input type='text' name='response' />
</body>
</html>

app.ts:(虽然在 js 中)

var response;

function ajaxFunction() {
    var ajaxRequest;  // The variable that makes Ajax possible!
    var response;

    try {
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e) {
        // Internet Explorer Browsers
        try {
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function () {
        if (ajaxRequest.readyState == 4) {
            response.innerHTML = "hi";

        }
    }
    ajaxRequest.open("GET", "http://localhost:8080", true);
    ajaxRequest.send(null);
}


window.onload = () => {
    response = document.getElementById('content');
};

我现在在 Chrome 的开发工具中收到“已取消”的网络请求。

【问题讨论】:

  • 似乎您遗漏了很多服务器代码。您能否粘贴整个内容,以便我们知道真正缺少什么或我们看不到的地方
  • 其实就是这样,差不多,我已经添加了nodejs的require语句。
  • 你的代码减少是否改变了结果
  • 不 :( 我刚刚删除了一些不需要的上下文,在我发布到 SO 之前,我已经尝试过这些以及许多其他可能的修复。
  • 你知道,如果你从桌面打开 default.htm 并尝试 AJAX 到服务器,比如...http://localhost:8080...你是不允许这样做的。

标签: javascript node.js


【解决方案1】:

新答案:

如果您在 onreadystatechange 处理程序中记录一些值,您会得到什么?

ajaxRequest.onreadystatechange = function () {
    
    console.log('ajaxRequest.readyState=', ajaxRequest.readyState, ajaxRequest.status);
    
    if (ajaxRequest.readyState == 4) {
        document.myForm.response.value = ajaxRequest.responseText;
    }
}

原答案:

有几种可能发生。

您的 ajaxRequest 变量是 ajaxFunction() 的本地变量,并且可能在函数执行后被垃圾回收。

尝试将ajaxRequest 移到ajaxFunction() 之外,如下所示:

var ajaxRequest;  // The variable that makes Ajax possible!

function ajaxFunction() {
    ... rest of your client code.
}

这样,在函数被调用后,变量仍然在作用域内。

或者,如果您的客户端运行在与服务器不同的域上(例如 http://localhost:8081/http://localhost:8080/),您可能会遇到跨域安全问题。

你能检查浏览器是否真的发出请求(即检查浏览器的开发工具而不是服务器上的)?无论您使用哪种浏览器,开发工具中都应该有一个“网络”选项卡。

查看CORS (Cross-Origin Resource Sharing) 的文档以了解可能发生的情况。

编辑:下面是对跨域安全错误以及如何在标准 Node.js 服务器中解决它的一个很好的概述:http://bannockburn.io/2013/09/cross-origin-resource-sharing-cors-with-a-node-js-express-js-and-sencha-touch-app/

此答案显示了如何在 Connect 服务器中添加标头: How can I add CORS-Headers to a static connect server?

【讨论】:

  • 从函数中取出 ajaxRequest 不起作用。在 Chrome 的开发工具 > 网络中,我得到 {Method: "GET", Status(Text): "304 Not Modified", Type: "text/html", Initiator: "Other", Size(Content): "338B ( 1.0KB)", 时间(延迟): "6ms (5ms)"}
  • 当我只加载页面而不使用 VS 时,我得到以下信息:{Method: "GET", Status(Text): "Success", Type: "text/html", Initiator :“其他”,大小(内容):“0(1.0KB)”,时间(延迟):“1ms(1ms)”}
  • 当您按下按钮时,您是否看到开发工具中显示了一个新请求?您能否在 onreadystatechange 函数中注销消息/值以便知道它何时运行?
  • 好吧,每次我点击我上面提到的按钮都会重新加载,但我想这只是页面本身。单击按钮时没有其他内容。
  • 哦,我没有在您的标记中看到表单。现在试试这个来阻止提交表单:&lt;button onclick="ajaxFunction(); return false;"&gt;request&lt;/button&gt;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多