首页 > 解决方案 > 为什么我的 http://localhost:8080 没有在 mac 上的 node.js 中加载

问题描述

所以我对 node.js 很陌生,而且我在 mac 上。我正在向 W3schools 学习,我必须在本地主机上运行 myfirst.js,但我不断收到此错误:

此页面不工作 localhost 没有发送任何数据。ERR_EMPTY_RESPONSE

这是代码:

const https = require('https');
https.createServer(function (req,res){
   res.writeHead(200, {'content-type':'text/html'});
  res.send('Hello world!');
}).listen(8080);

我在终端中运行了这段代码:

Macs-MBP:~ mac$ node /Users/mac/test/myfirst.js

终端命令有效,但是当我转到浏览器并运行时:http://localhost:8080

我只是不断收到上述错误

我将如何解决这个问题?

标签: node.js

解决方案


试试这样:

const http = require('http');
var server = http.createServer(function (req,res){
  res.writeHead(200, {'content-type':'text/html'});
  res.write('<html><body><p>Hello world!</p></body></html>');
  res.end();
});
server.listen(8080);
console.log('Node.js web server running..')

推荐阅读