【问题标题】:Confused about Express, node.js terminology对 Express、node.js 术语感到困惑
【发布时间】:2020-04-25 12:15:47
【问题描述】:

我是网络开发的新手。我目前正在学习 express.js。以下代码和文本来自他们的文档。

const express = require('express')

const app = express()

const port = 3000

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))

This app starts a server and listens on port 3000 for connections.

我对这里的服务器感到困惑。哪一行代码指的是“创建服务器”? express 应用程序是服务器本身,还是仅侦听端口 3000 上的请求,而服务器是其他东西?

非常感谢!

【问题讨论】:

  • line app.listen 在端口 3000 启动您的服务器。如果您浏览 localhost:3000,您将在那里获得您的 Hello World。建议你在跳express之前先学习基本的node和http模块,

标签: node.js express server


【解决方案1】:

Express 基本上是 Node Js 的框架,像 Python 有 Django,Java 有 Spring 等。

当您在节点 js 中创建服务器时,您使用 HTTP 模块,通过内部函数表达它们提供 listen 功能。

当您使用 Node 创建服务器时,您使用以下代码

http.createServer(function (req, res) { res.write('Hello World!'); res.end(); //end the response }).listen(8080);

所以在 node http 模块中有监听功能 & 在 express js express 模块中有监听功能。

app.listen 创建一个新服务器。明确地说,没有任何 CreateServer 术语。所以 express 使用起来非常灵活。

请关注此网址http://expressjs.com/en/guide/writing-middleware.html

【讨论】:

    【解决方案2】:

    在您调用 listen 的那一刻,服务器将开始运行,侦听您定义的 PORT。 这是您的代码的逐行注释版本:

    //We are creating the express app by setting it to the app variable.
    const express = require('express')
    //The express object
    const app = express()
    //The port
    const port = 3000
    /*
    .get is telling to the express object that when it gets that route ('/')
    it should give the specified response : 'Hello World!' for our case.
    It takes in 2 arguments: 
    (1) the url - the route
    (2) the function that tells express what to send back as a response for the 
    request - the callback function
    */
    app.get('/', (req, res) => res.send('Hello World!'))
    
    //.listen is going to bind the application to the port 3000.
    app.listen(port, () => console.log(`My awesome app is listening at 
    http://localhost:${port}`))
    

    要了解concepts node和express的区别,I found this response usefull

    【讨论】:

      【解决方案3】:

      正如你所说,整个块“创建”服务器,它不仅仅是“创建”服务器的一行。

      使用 node 和 npm 安装 express const express = require('express')

      在这一行中你使用 express 框架 const app = express()

      在这一行中,您设置了一个端口 const port = 3000

      在这一行中,您创建主根 app.get('/', (req, res) => res.send('Hello World!'))

      这一行使用端口并向上运行您的网络服务器 app.listen(port, () => console.log(Example app listening at http://localhost:${port}))

      如您所见,所有这些组合起来“创建”了服务器

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-13
        • 2018-11-13
        • 2014-02-23
        • 1970-01-01
        • 1970-01-01
        • 2012-07-12
        • 1970-01-01
        • 2011-04-28
        相关资源
        最近更新 更多