如何解决此“本地主机意外关闭连接”错误?

Joh*_*moe 7 routing node.js express

我正在阅读Chris Sevilleja 的“ Mean Machine:JavaScript 堆栈的初学者实用指南”。我的问题在第 60 页。根据本书的说明,我创建了一个小server.js文件以及package.json, 并用于npm install创建node_modules folder并用适当的模块填充它。当我运行“server.js”时。我在终端中收到一条消息,该消息运行console.log()我放置在程序末尾的消息,因此我知道程序已执行。

但是当我转到 Chrome 并https://localhost:8080在搜索栏中输入' " 时,我收到以下错误消息:

无法访问此站点

localhost 意外关闭了连接。

ERR_CONNECTION_CLOSED

我花了一个多小时试图弄清楚这一点,但我很迷茫。如果我使用“http”而不是“https”,则加载需要很长时间(我等了大约 5 分钟)。我已经检查过 Chrome 中是否有异步 DNS 标志或其他东西,并确认它已启用。我尝试在终端上执行“$ lsof -i:8080”并得到:

命令 PID 用户 FD 类型设备大小/关闭节点名称节点 6188 23u IPv6 0x3a96cd0448d7ba87 0t0 TCP *:http-alt (LISTEN)

(不太确定它的作用,但我在解决类似问题的网页上看到它,响应者指示该人这样做。)我也尝试在 Safari 上访问它并收到相同的消息。

我的代码如下:

var express = require('express');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');

var port = process.env.PORT || 8080; // set the port for our app

var app = express(); // define our app in terms of Express
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json);

// configure out app to handle CORS requests
app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type, Authorization');
    next();
});

// log all requests to the console
app.use(morgan('dev'));

// API routes

// basic route for the home page
// route, not middleware, so no 'next' parameter
app.get('/', function(req, res) {
    res.send('Welcome to the home page!');
});

// get an instance of the express router
var apiRouter = express.Router();

// test route to make sure everything is working
// accessed at GET http://localhost:8080/api
apiRouter.get('/', function(req, res) {
    res.json({message: 'Welcome to our API.'});
});

// mount apiRouter on our app
// they will all be prefixed with /api
app.use('/api', apiRouter);

// start the server on the port we indicated on line 6
app.listen(port);
console.log('Magic happens on port ' + port);
Run Code Online (Sandbox Code Playgroud)

获得我的'res.send('欢迎来到主页!');'的任何建议 要显示的消息会很棒。

提前致谢。我已尽力描述问题,但如果您需要任何其他信息,请告诉我。

有点跟进:我正在使用 SublimeText。我可以使用更复杂的 IDE 识别/解决这个问题吗?

小智 4

在 Chrome 中,将“ http://localhost:8080 ”替换为“ https://localhost:8080 ”。删除 s。