【问题标题】:Why use http module to set port as app.listen also sets port?为什么使用 http 模块设置端口作为 app.listen 也设置端口?
【发布时间】:2017-07-08 00:23:32
【问题描述】:
var express = require("express");
var app = express();

// sets port 8080 to default or unless otherwise specified in the environment
app.set('port', process.env.PORT || 8080);

app.get('/', function(req, res){
    res.send('hello world');
});

// Only works on 3000 regardless of what I set environment port to or how I set
// [value] in app.set('port', [value]).
// app.listen(3000);
app.listen(app.get('port'));

通过使用上面的代码,我们可以设置我们的 node.js 端口。 但有时我发现在许多网站上人们都在使用 http 模块来设置 nodejs 端口

http.createServer(app).listen(app.get('port'),
  function(){
    console.log("Express server listening on port " + app.get('port'));
});

有人会告诉什么时候使用哪个代码吗?

【问题讨论】:

  • 这是一个偏好问题。 express在后台使用http模块。

标签: javascript node.js http express server


【解决方案1】:

在使用“express”节点模块时使用app.listen 函数。

在使用“连接”节点模块时使用http.createServer(app).listen 函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    相关资源
    最近更新 更多