我之前做了一些节点实验
以下代码将"aaa"输出到控制台,并且浏览器会按预期等待响应.
var http = require("http");
http.createServer(function (req, res) {
//res.writeHead(200);
console.log("aaa");
//res.end("hello");
//console.log("test111");
//res.end("bye");
}).listen(5555);
Run Code Online (Sandbox Code Playgroud)
输出:
aaa
Run Code Online (Sandbox Code Playgroud)
但是,只要我取消注释第一个res.end,节点就会在一次请求中将"aaa"写入控制台两次!
var http = require("http");
http.createServer(function (req, res) {
res.writeHead(200);
console.log("aaa");
res.end("hello");
//console.log("test111");
//res.end("bye");
}).listen(5555);
Run Code Online (Sandbox Code Playgroud)
输出:
aaa
aaa
Run Code Online (Sandbox Code Playgroud)
最后,当我取消评论一切时,
var http = require("http");
http.createServer(function (req, res) {
res.writeHead(200);
console.log("aaa");
res.end("hello");
console.log("test111");
res.end("bye");
}).listen(5555);
Run Code Online (Sandbox Code Playgroud)
输出:
aaa
test111
aaa
test111
Run Code Online (Sandbox Code Playgroud)
知道为什么每个请求都会执行两次console.log语句吗?
在第一个示例中,浏览器没有得到回复并停在那里.
在第二个示例中,浏览器确实得到了回复,然后继续请求第二个请求的favicon.
尝试也记录请求网址:
var http = require("http");
http.createServer(function (req, res) {
console.log("aaa", req.url);
res.end("bye");
}).listen(5555);
Run Code Online (Sandbox Code Playgroud)
你会看到服务器正在运行:
aaa /
aaa /favicon.ico
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
666 次 |
| 最近记录: |