【问题标题】:Node.js HTTP Server- Taking long time to load and is not sending dataNode.js HTTP 服务器 - 加载时间长且不发送数据
【发布时间】:2019-12-31 21:03:27
【问题描述】:

我正在学习 node.js,在使用 HTTP 模块时,我尝试按照视频导师的指示由自己的服务器创建,但我的服务器没有在端口 3000 和端口 8000 发送任何响应。

*

const http = require('http');
const server = http.createServer((req, res) => { 
    if(req === '/'){ 
        res.write('Hello world, first program in server using http module');
        res.end();
    }
    if(req === '/api/courses'){
        res.write(json.strigify([1,2,3]));
        res.end();
    }
});
server.listen(8000);
console.log('Listening @port 8000');

*

【问题讨论】:

  • 上述程序的输出:PS D:\Programming note-self\projects> node app.js Listening @port 8000
  • 视频导师有没有教你严格比对req === '/'?在网上查找一些createServer 使用示例,看看他们如何检查请求通过哪个路由。
  • 是的,他指示进行严格的比较,但我想我发现了错误,我只是在比较时忘记使用req方法的url属性,现在问题解决了。感谢您的意见。使用 req.url === '/' 帮助了我。

标签: javascript node.js http httpmodule


【解决方案1】:

严格的比较req === '/' 是将请求对象与字符串进行比较,这种比较永远不会为真。

您可能打算使用:req.url === '/'

【讨论】:

    猜你喜欢
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 2017-04-15
    相关资源
    最近更新 更多