Node.js 点击URL时在nodejs中的请求和响应
} 当我访问localhost:3000时, console.log(数据)、console.log(“----------------”)和console.log(内容)在console中显示4次Node.js 点击URL时在nodejs中的请求和响应,node.js,Node.js,} 当我访问localhost:3000时, console.log(数据)、console.log(“----------------”)和console.log(内容)在console中显示4次 有人能解释一下为什么会这样吗?这很正常-你的浏览器会打不止一个电话 例如,大多数浏览器都会调用grab/favicon.ico 尝试记录url: const http=require('http'); const fs=require('fs'); var server=http.createSe
有人能解释一下为什么会这样吗?这很正常-你的浏览器会打不止一个电话 例如,大多数浏览器都会调用grab/favicon.ico 尝试记录url:
const http=require('http');
const fs=require('fs');
var server=http.createServer(getFromClient);
server.listen(3000);
console.log("server start");
function getFromClient(req,res){
fs.readFile('./index.html','utf-8',(error,data)=>{
console.log(data);
console.log("-------------");
var content=data.replace(/dummy_title/g,'Title will be here').replace('dummy_content','Content will be here');
console.log(content);
res.writeHead(200,{'Content-Type':'text/html'});
res.write(content);
res.end();
});
你会看到他们叫什么。
此问题的解决方案可以是检查请求URL是否正在获取favicon.ico。只需添加req.url!='/favicon.ico'到你的代码
console.log(req.url);
function getFromClient(req,res){
if (req.url != '/favicon.ico') {
fs.readFile('./index.html','utf-8',(error,data)=>{
console.log(data);
console.log("-------------");
var content=data.replace(/dummy_title/g,'Title will be here').replace('dummy_content','Content will be here');
console.log(content);
res.writeHead(200,{'Content-Type':'text/html'});
res.write(content);
res.end();
});
}
}