【问题标题】:Local Host is not sending any data本地主机未发送任何数据
【发布时间】:2022-02-02 02:22:37
【问题描述】:

每当我在端口“8000”上运行此节点服务器时

const http=require('https')
const PORT=8000

const server=http.createServer()

server.on('request',(req,res)=>{

    if (req.url==='friend'){

        res.writeHead(200,{
            'Content-Type':'text/plain',
        })
    
        res.end(JSON.stringify({
            id:1,
            name:'Sir Issac Newton',
        }))

    }

    if (req.url==='foe'){
        res.writeHead(200,{
            'Content-Type':'text/plain',
        })

        res.end('The Enemy is Ego Bro')
    }


})


server.listen(PORT,()=>{
    console.log(`the respnse is exectued at ${PORT}`)
})

我在 Borwser 上收到一条错误消息:

localhost 没有发送任何数据。 ERR_EMPTY_RESPONSE

我尝试更改端口,但仍然显示此错误。请问我应该怎么做并解释这个错误是什么。谢谢!

【问题讨论】:

    标签: javascript node.js web localhost node-modules


    【解决方案1】:

    这段代码有3个问题。

    1. 您应该将const http=require('https') 更改为const http=require('http')。如果您想使用 HTTPS,请参阅 nodejs 文档了解如何配置 https 服务器

    2. 在 nodejs HTTP 请求 URL 中以 / 开头并且您的条件语句不起作用

    3. 因为请求的 URL 与条件语句不匹配服务器没有响应任何事情而发生此错误。

    您应该像这样更改代码:

    const http=require('http')
    const PORT=8000
    
    const server=http.createServer()
    
    server.on('request',(req,res)=>{
    
        if (req.url==='/friend'){
    
            res.writeHead(200,{
                'Content-Type':'text/plain',
            });
        
            res.end(JSON.stringify({
                id:1,
                name:'Sir Issac Newton',
            }));
    
           return;
        }
    
        if (req.url==='/foe'){
            res.writeHead(200,{
                'Content-Type':'text/plain',
            });
    
            res.end('The Enemy is Ego Bro');
    
            return;
        }
    
        res.writeHead(400,{
            'Content-Type':'text/plain',
        });
    
        res.end('URL not match');
    })
    
    
    server.listen(PORT,()=>{
        console.log(`the respnse is exectued at ${PORT}`)
    })
    

    【讨论】:

      猜你喜欢
      • 2019-08-18
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      • 1970-01-01
      • 1970-01-01
      • 2017-06-05
      相关资源
      最近更新 更多