![](/img/trans.png)
[英]How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)
[英]localhost:8080 is not loaded for Node.js on Mac OS X
我正在关注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。 当我尝试检查localhost:8080时,什么也没有发生,只有等待。 但是,当我尝试输入localhost时,会看到虚拟的“它有效!”。 信息。 可能我的计算机也正在运行。 我该如何摆脱呢? 我尝试停止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服务器的默认index.html,默认情况下在端口80上运行。您的nodejs服务器在端口8080上进行侦听,因此没有问题,并且两者可以共存。
如果您仍然想停止apache服务器,
sudo service apache2 stop
可以使用。
并且如果端口8080上正在运行任何服务器,然后尝试在端口8080上启动http服务器,则会收到Error: listen EADDRINUSE
如果服务器启动时没有出现此错误,则可以确定没有其他任何运行在端口8080上
编辑:当来自客户端(浏览器)的请求request.on(end)
时,将触发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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.