gpt4 book ai didi

node.js - 来自 node.js 新手的一些问题

转载 作者:搜寻专家 更新时间:2023-11-01 00:34:21 24 4
gpt4 key购买 nike

我刚开始学习 node,我在 Fedora 12 上使用 node-v0.4.11。它安装没有任何错误,我能够运行一些基本程序,但有些事情我无法弄清楚

If i create a server at a port and then if i stop node using Ctrl+C i cannot use that port again for starting a server without restarting the system.

我的代码是这样的

var port=8080;
var count=0;
var http=require('http');
var server = http.createServer(function(req, res) {
count++;
console.log('request no '+count+' received');
res.writeHead(200);
res.end('you are at port '+port);
});
server.listen(port);
console.log('server started at port '+port);

现在,当我保存文件并执行它时,服务器启动。但是当我从 shell 停止服务器时,我无法在我之前启动的端口(在本例中为端口 8080)再次启动服务器。这很糟糕,因为每次我都必须对此进行更改文件我也必须更改端口号。我可以停止这种行为吗?

编辑:

这是我尝试再次在同一端口启动服务器时遇到的错误

Server started at 8080

node.js:203
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: listen EADDRINUSE
at errnoException (net_uv.js:557:11)
at Array.<anonymous> (net_uv.js:632:28)
at EventEmitter._tickCallback (node.js:195:26)

在我使用 Ctrl+C 终止 node 后,我看到了进程列表,我发现 node 仍在运行。所以我杀了它并再次检查进程列表以确保它已经死了(我在进程列表中看不到它)。现在我再次尝试在同一端口启动服务器,但出现与上述相同的错误。一旦我停止服务器并从浏览器发出请求,请求就会永远挂起(它一直在等待)。


My next problem is that in the above when the server starts and i make the first request count is incremented 3 times and i can see 3 messages at the console. This is just for the first request,if i make more requests count is just incremented once. Whats wrong?

this problem is solved


My next problem is that if i change res.writeHead(200); to res.writeHead(404); or any other valid status code like 300 node gives error at the command line but these are valid status codes and the server should start and respond to each request according the status code like Not found for 404. What am i doing wrong?

this problem is solved


I am not able to use Firebug's 'Net' tab to monitor requests when i send requests to the server created by Node. Is there a way to do so?

感谢您的支持。

最佳答案

i cannot start the server again at the port i started before

你不应该看到这种行为,我无法重现它。当您尝试再次启动服务器时是否收到错误消息?它是什么?停止服务器后,您是否在进程列表中看到任何 node 进程?如果是这样,您可以在杀死它们后启动您的服务器吗?


count is incremented 3 times and i can see 3 messages at the console

您的浏览器正在发送多个请求。例如,在 Chrome 中,您可能会收到 (1) 预取请求(Chrome 下载它认为您想要的页面),(2) 实际页面请求,以及 (3) 请求对于 favicon.ico;您的 Node 应用正在监听所有 请求,而不仅仅是对 / URL 的请求。初始请求后,浏览器会缓存 favicon 等,不需要再次请求。

尝试将 console.log(req.url); 添加到您的回调中,然后查看浏览器要求的 URL。


any other valid status code like 300 node gives error at the command line

我无法重现这个问题。您收到什么错误?


I am not able to use Firebug's 'Net' tab to monitor requests when i send requests to the server created by Node

我也无法重现这一点。 Firebug 和其他客户端调试工具不知道也不关心服务器上运行的是什么技术;它只是说 HTTP。

关于node.js - 来自 node.js 新手的一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7410413/

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