node.js的安装与第一个hello world、node.js的初始化

1、下载node.js文件

2、windows下点击安装  重复下一步即可

3、编辑工具  EditPlus编辑器

4、新建保存目录的文件夹,并新建一个文本文档

5、打开EditPlus编辑器  打开新建的文本文档--选择“文件”-选择“另存为副本”   文件名后缀是.js  保存类型:选择“所有文件”  编码选择“utf-8”  保存

 保存之后,编写console.log();

6、运行   在目录文件夹中  按住shift 右键选择“在此处打开命令窗口” -    在命令窗口中  输入node n1_hello.js

7、初始化

var http = require('http');

http.createServer(function (request, response) {

    response.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'});  
    if(request.url!=="/favicon.ico"){  //清除第2此访问  
        console.log('访问');  
        response.write('hello,world');  
        response.end('hell,世界');//不写则没有http协议尾,但写了会产生两次访问  
    } }).listen(
8888); //监听8888端口 响应的数据 // 终端打印如下信息 console.log('Server running at http://127.0.0.1:8888/');

注:a、引入 required 模块   var http = require('http');

       b、http.createServer() 方法创建服务器,并使用 listen 方法绑定 8888 端口。 函数通过两个参数 request, response 来接收和响应数据

http.createServer(function (request, response) {
    
}).listen(8888);

 

       c、// 发送 HTTP 头部     // HTTP 状态值: 200 : OK     // 内容类型: text/plain   

 response.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'}); 

 

      d、 // 发送给页面的响应数据 "Hello World" response.end();  如果不写的话  页面会一直再请求,但写了会产生两次访问 
      f、由于写了response.end();会产生两次访问,
为了清除第二次访问我们添加if判断

          if(request.url!=="/favicon.ico"){  //清除第2此访问    }

     g、 response.write('hello,world');  是给页面写入响应后的数据 response响应数据

     k、/*  
           启动服务  
           cmd下执行:  
           node  n1_hello.js  
           浏览器访问:http://localhost:8888 
          */     

     

 

posted @ 2018-04-10 15:41  88旧港  阅读(248)  评论(0编辑  收藏  举报