【问题标题】:Node export writing on console twice..Why? [duplicate]节点导出在控制台上写入两次..为什么? [复制]
【发布时间】:2020-03-04 14:55:25
【问题描述】:

myfirst.js

var http = require("http");
var firstModule = require("./myfirstExportModule");

http.createServer(function(req, res){
    res.writeHead(200, {'content-Type':'text/html'});
    res.write('first name on console. ');
    firstModule.firstname("name");
    res.end('');
}).listen(3000);

console.log("listening on port 3000...");

myfirstExportModule.js

function firstname(name){
    console.log('<br>first Name is: '+name);
}

module.exports = {
    firstname:firstname
} 

我在控制台上得到两个输出,如下所示

first Name is: Name
first Name is: Name

谁能解释一下原因?

【问题讨论】:

标签: node.js


【解决方案1】:

您的请求之一是针对 favicon.ico,因为这是浏览器在没有为特定域缓存的 favicon 时会请求的内容。

Web 服务器的所有请求都必须查看所请求的实际资源,并根据所请求的确切资源做出适当的响应。

如果你把代码写成

http.createServer(function(req, res){
    res.writeHead(200, {'content-Type':'text/html'});
    res.write('first name on console. ');
    firstModule.firstname("name");
    console.log(req.url);    // here console the requested url
    res.end('');
}).listen(3000)

然后你会得到

<br>first Name is: name
/
<br>first Name is: name
/favicon.ico

为了防止这种情况,您可以检查 request.url 中的特定路径,并且仅在路径符合您的预期时应用您的逻辑。

http.createServer(function(req, res){ 
 if (request.url === "/") {
  //... Do your code accordingly
 } else { 
  //....Do your code accordingly
 } 
}).listen(3000);

【讨论】:

    猜你喜欢
    • 2021-08-31
    • 2022-06-16
    • 2021-01-09
    • 2021-09-29
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 2014-11-20
    相关资源
    最近更新 更多