localhost:8080 未在 Mac OS X 上为 Node.js 加载

localhost:8080 is not loaded for Node.js on Mac OS X

本文关键字:上为 Node js 加载 OS 8080 未在 Mac localhost      更新时间:2023-09-26

我正在遵循 Node 的教程.js我有以下代码:

var http = require("http");
http.createServer(function (request, response){
        request.on("end", function() {
                response.writeHead(200, {
                        'Content-Type': 'text/plain'
                });
                response.end('Hello HTTP!');
        });
}).listen(8080);

我已将该代码保存为 http.js。当我尝试检查本地主机:8080时,没有任何反应,只是等待。但是,当我尝试输入本地主机时,我看到虚拟的"它有效!"消息。可能我的计算机中也正在运行某些内容。我怎样才能摆脱它?我尝试停止 apache 并删除/Library/WebServer/Documents 中的所有内容。

const http = require('http');
http.createServer( function (request, response) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Hello World'n');
}).listen(8080);

这是nodeJS中的一个简单的http服务器。

"成功了!" 是成功安装/运行 Apache http 服务器的默认索引.html默认情况下在端口 80 上运行。并且您的 NodeJS 服务器正在侦听端口 8080,因此没有问题,两者可以共存。

如果您仍然想停止Apache服务器,则无论如何

sudo service apache2 stop

可以使用。

如果有任何服务器在端口 8080 上运行,然后您尝试在端口 8080 上启动 HTTP 服务器,您将收到Error: listen EADDRINUSE 如果您的服务器启动时没有此错误,您可以确定,端口 8080 上没有其他运行

编辑: 当来自客户端(浏览器)的请求结束时,将触发request.on(end)。但在您的情况下,浏览器仍在等待您的响应,并且请求正在等待中。 一旦您调用response.end(),立即触发request.on(end)

现在我将修改您的代码,以这种方式工作,只需进行少量修改

var http = require("http");
http.createServer(function (request, response){
        response.end('Hello HTTP!');  //change
        request.on("end", function() {
                //should be outside or removed
                /*response.writeHead(200, {
                        'Content-Type': 'text/plain'
                });*/
        });
}).listen(8080);

尝试response.send()而不是response.end()

您不会将信息发送回客户端。

请参阅:http://expressjs.com/en/api.html

编辑

评论是正确的,对不起。阅读太快。

请参阅:https://nodejs.org/api/http.html#http_http_createserver_requestlistener

您需要一条接收路线。使用http.get('/', someFn)