【问题标题】:When in the browser I typed 'localhost:3005', it works a long time, before display first result当我在浏览器中输入 \'localhost:3005\' 时,它工作了很长时间,然后才显示第一个结果
【发布时间】:2022-11-20 01:16:14
【问题描述】:

我在 node.js 上写了简单的服务器运行脚本

const http = require('http')

let requestsCount = 0
const server = http.createServer((request, response) => {
    requestsCount++
    response.write(`Leo Garsia ${requestsCount}`)

})

server.listen(3005, () => {
    console.info('Server is Running on port 3005')
})

当我在浏览器中输入“localhost:3005”时,它运行了很长时间,然后才显示第一个结果。 (约10分钟) 为什么会打嗝?

然后当我刷新浏览器时,它 requestsCount 增加了两次。并显示 2、4、6 等结果。 很有趣为什么?

【问题讨论】:

    标签: node.js http


    【解决方案1】:

    当我在浏览器中输入“localhost:3005”时,它运行了很长时间,然后才显示第一个结果。 (约10分钟)

    您的响应永远不会结束,因为您的代码在 response.write 之后缺少 response.end() 语句。因此,浏览器会等到超时(10 分钟),然后显示到目前为止收到的内容。

    然后当我刷新浏览器时,它 requestsCount 增加了两次。并显示 2、4、6 等结果。很有趣为什么?

    我怀疑另一个请求是浏览器对收藏夹图标发出的请求,请参阅here

    【讨论】:

      【解决方案2】:

      正如 Heiko TheiBen 所说,我搞砸了 response.end() 我已经用“快递”替换了代码。 现在,当我输入“localhost:3005/leo”时,结果会立即出现。

      const express = require('express')
      
      const app=express();
      let requestsCount = 0
      app.listen(3005, () =>{
         console.log('Server is running on port 3005...')
      })
      
      app.get('/leo', (request, response)=>{
          requestsCount++
          response.write(`Request URL is, ${request.url}  count is, ${requestsCount}`)
          response.end()
          console.info(`Request URL is, ${request.url}  count is, ${requestsCount}`)
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-03-18
        • 2016-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-30
        • 1970-01-01
        相关资源
        最近更新 更多