我爱编程

node.js 学习一 之 hello world

2016-12-24  本文已影响47人  skuare520

什么是node.js

node.js 的劣势和解决方案

安装

安装 node.js 官网下载
测试是否安装成功
npm -v
node -v

hello world

var  http  =  require('http');  
// http 创建一个服务
// request - 浏览器向服务器请求发出的对象
// response - 服务器向浏览器写回的对象
http.createServer(function  (request,  response)  {  
    response.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'});  
    console.log('访问');  
    response.write('hello,world');  
}).listen(8000);  
console.log('Server  running  at  http://127.0.0.1:8000/');  
  
/*  
启动服务  
cmd下执行:  
node  n1_hello.js  
浏览器访问:http://localhost:8000  
*/    

浏览器:
可以看到虽然输出了文字,但是浏览器还一直在loading
因为缺少了一句response.end(),http协议实际还未结束

01_hello_loading.png

增加response.end

var  http  =  require('http');  
// http 创建一个服务
// request - 浏览器向服务器请求发出的对象
// response - 服务器向浏览器写回的对象
http.createServer(function  (request,  response)  {  
    response.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'});  
    console.log('访问');  
    // write 输出但http协议未执行完毕
    response.write('hello,world');  
    response.end('hell,世界');//不写则没有http协议尾,但写了会产生两次访问  
}).listen(8000);  
console.log('Server  running  at  http://127.0.0.1:8000/'); 

response.end中也可以输入
然后从控制台中可以看到,输入了两次"访问"


01_hello_console.png

这是因为浏览器会再次访问 favicon 这个资源

01_hello_chrome.png

清除二次访问

var  http  =  require('http');  
// http 创建一个服务
// request - 浏览器向服务器请求发出的对象
// response - 服务器向浏览器写回的对象
http.createServer(function  (request,  response)  {  
    response.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'});  
    if(request.url!=="/favicon.ico"){  //清除第2此访问  
        console.log('访问');  
        // write 输出但http协议未执行完毕
        response.write('hello,world');  
        response.end('hell,世界');//不写则没有http协议尾,但写了会产生两次访问  
    }  
}).listen(8000);  
console.log('Server  running  at  http://127.0.0.1:8000/');  
上一篇 下一篇

猜你喜欢

热点阅读