Nodejs 菜鸟教程学习-创建第一个应用

注:为了解学习,都是参照http://www.runoob.com/nodejs/nodejs-tutorial.html书写,做下笔记。

对于Nodejs开发来说,在开发一个应用时,我们不仅仅是实现了一个应用,而且同时实现了HTTP服务器所要完成的事。

Nodejs应用的主要组成:

  1. 引入required模块:使用require命令载入nodejs功能模块;
  2. 创建服务器:服务器可以监听客户端的请求,类似于Apache,Nginx等HTTP服务器;
  3. 接受请求和响应请求:服务器接受到HTTP请求并响应请求的数据。

第一步,新建文件夹作为工程目录(projectdemo),新建文件http.createServer.js,内容如下:(Nodejs中引入模块一般都是这种方法,比如文件,事件,npm安装的功能)

//引入http模块
var http = require('http');

//使用获取到的http实例创建server,端口号为8809
http.createServer(function(request, response){
    //为http响应的写入消息头
    response.writeHead(200, {'Content-type':'application/json'});
    //为http响应写入消息体
    response.end('nodejs!!!~.~');
}).listen(8809);

console.log('Server is running at http://127.0.0.1:8809/');

在文件夹内按住shift后右键,“在此处打开命令窗口”,打开cmd窗口:

D:
odejsprojectdemo>node http.createServer.js
Server is running at http://127.0.0.1:8809/

此时就可以在浏览器中访问http://127.0.0.1:8809/

原文地址:https://www.cnblogs.com/fengdeng/p/5806938.html