首页 > 解决方案 > node.js 的简单服务器测试不起作用,没有输出

问题描述

我对 node.js 很陌生,我想知道一般测试以下类型代码的最佳方法。现在,我将这一切作为 netbeans node.js 项目中的一个文件来完成。我没有得到任何输出,输出应该是“HELLO SERVER”。

它通常编译没有错误,但没有输出,其他时候它说

"throw er; // 未处理的 'error' 事件错误:监听 EADDRINUSE :::8000"

我已经知道这个拒绝意味着什么,我认为它只是在我单击两次运行时这样做,因为然后端口被第一次运行占用。

我已经尝试过多个端口,它可以工作但没有输出......

我应该以其他方式对此进行测试吗?为什么没有输出?输出应该是“HELLO SERVER” 谢谢。

var http = require("http");
http.createServer(function (request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    request.on("data", function (chunk) {
        response.write(chunk.toString().toUpperCase());
    });
    request.on("end", function () {
        response.end();
    });
}).listen(8000);

var http = require("http");
var request = http.request({
    hostname: "localhost",
    port: 8000,
    method: "POST"
}, function (response) {
    response.on("data", function (chunk) {
        process.stdout.write(chunk.toString());
    });
});
request.end("Hello Server");

标签: javascriptnode.js

解决方案


这意味着您的端口8000已被另一个进程使用。该进程可能是您的服务器的旧实例仍在运行(未正确退出),仍在占用该端口。

尝试使用端口查找进程8000并杀死它

在 Linux 上

fuser -k 8000/tcp

在 Windows 上

netstat -ano | findstr :8000
// Find the value of the PID (last column to the right)
taskkill /PID {pid_value} /F

推荐阅读