javascript - Express.js 中的 app.set('port', 8080) 与 app.listen(8080)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25337222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript - app.set('port', 8080) versus app.listen(8080) in Express.js
提问by peco
I've been trying to use Express.js to launch a website. At first, I was using
app.set('port', 8080)
but the browser was unable to connect to the page. Afterwards, I changed the code to app.listen(8080)
and the webpage appeared normally.
我一直在尝试使用 Express.js 来启动一个网站。一开始,我正在使用,
app.set('port', 8080)
但浏览器无法连接到该页面。后来我把代码改成了app.listen(8080)
,网页就正常出现了。
This led me to wonder, what is the difference between these two functions?
这让我想知道,这两个功能有什么区别?
回答by Arnelle Balane
app.set('port', 8080)
is similar to setting a "variable" named port
to 8080
, which you can access later on using app.get('port')
. Accessing your website from the browser will really not work because you still didn't tell your app to listen and accept connections.
app.set('port', 8080)
类似于设置一个名为port
to的“变量” 8080
,您可以稍后使用app.get('port')
. 从浏览器访问您的网站确实不起作用,因为您仍然没有告诉您的应用程序侦听和接受连接。
app.listen(8080)
on the other hand listens for connections at port 8080
. This is the part where you're telling your app to listen and accept connections. Accessing your app from the browser using localhost:8080
will work if you have this in your code.
app.listen(8080)
另一方面在端口监听连接8080
。这是您告诉应用程序侦听和接受连接的部分。localhost:8080
如果您的代码中有此功能,则可以使用浏览器访问您的应用程序。
The two commands can actually be used together:
这两个命令实际上可以一起使用:
app.set('port', 8080);
app.listen(app.get('port'));
回答by Winnemucca
It is simple enough to declare a variable server at the bottom of the page and define the port that you want. You can console.log the port so that it will be visible in the command line.
在页面底部声明一个变量服务器并定义所需的端口非常简单。您可以对端口进行 console.log,以便它在命令行中可见。
var server = app.listen(8080,function(){
console.log('express server listening on port ' + server.address().port);
})
回答by Stack_Developer
For example:
例如:
var port = 8080
app.listen(port);
console.log(`Listening on port ${port}`);
Line by Line Explaination:
逐行说明:
var port = 8080;
=>Creates a variable(everything in javascript is an object) and sets the port location to localhost 8080 app.listen(port);
=>The application made using express module checks for any connections available and if yes then it connects and the application launches
console.log('Listening on port ' + port);
=>Displays the message onto the terminal once deployed successfully
var port = 8080;
=> 创建一个变量(javascript 中的所有内容都是一个对象)并将端口位置设置为 localhost 8080 app.listen(port);
=> 使用 express 模块创建的应用程序检查任何可用连接,如果是,则连接并启动应用程序
console.log('Listening on port ' + port);
=> 将消息显示到终端一旦部署成功