监听代码解释
var http=require('http')
http.createServer(function(request,response){
response.writeHead(200,{'Content-Type':"text/html"});
response.end("hello world");
}).listen(80);
console.log('start listen on 80 port');
1引入http模块
var http =require('http')
使用Node.js内置的http模块,用于处理网络请求
2创建服务器
http.createServer(function(request,response){
通过createServer方法创建服务器实例,接受一个回调函数的参数,该函数会在每次请求到达时被触发
3设置响应头
response.writeHead(200,{'Content-Type':"text/html"});
200:HTTP状态码表示成功
Content-Type:text/html:声明返回的内容的类型是html
4.返回响应内容
response.end("hello world");
结束响应流程,向客户端发送hello word
5.监听端口
}).listen(80);
服务器开始监听80端口
6.控制台日志
console.log('start listen on 80 port');
在终端打印服务器启动成功的提示
返回响应内容失败问题
localhost可以访问到响应内容,但127.0.0.1访问不到
IPv4 与 IPv6 的优先级问题
如果系统优先使用 IPv6,而服务器仅监听 IPv4 的 127.0.0.1
,可能导致访问不一致。
解决办法
在代码中显式绑定 IPv4 地址:
}).listen(80,'127.0.0.1');