node.js是服务器端JS,把d01_hollo.js 程序的改进为服务器程序:
// d02_hollo.js
var http=require('http');
http.createServer(function(request, response){ //请求对象;响应对象
response.writeHead(200, {'Content-Type':'text/html; charset=utf-8'});
//http文件头,输出类型:html文本类型/ utf-8编码
if(request.url!=='/favicon.ico'){ //清除避免2次访问
console.log('开始访问'); //后台输出: 开始访问
response.write('hello world'); //前端输出: hello world
response.end(''); //必须带内容;至少引号('')空字符串
}
}).listen(8000); //监听端口: 挂网时一般改为80
console.log('Server running at http://127.0.0.1:8000/');
cmd执行命令: node d02_hello.js
浏览器访问: http://localhost:8000
不写end()则缺失http协议尾,导致持续访问无法结束;
// 浏览器异常表现为持续访问/转圈圈
写了end()则产生2次访问:必须清除第2次访问(框架开发一般已清除);
// d02_hello.js 代码加入if判断处理
end(’’)就算无结束内容,必须带(’’)单引号 或("")双引号
// 二进制,可不带引号