nodeJs编写的简单服务器

 一、简单的nodeJs写的 http 服务器

1.先Hello world,创建最简单的 Node 服务器(server.js)

var http = require("http");

http.createServer(function(request, reponse) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
}).listen(8888);

执行: 

node server.js

1. var http = require("http")  表示请求NodeJs自带的 http 模块,并赋值给 http 变量

2.  http.createServer()  会返回一个对象,这个对象有一个 listen 方法,这个方法有一个Number类型的参数,该参数指定了HTTP服务器监听的端口号

3. 所以本段代码 会开启一个监听 8888 端口的服务器,我们可以通过打开浏览器,访问 http://localhost:8888/  来连接该服务器,我们会看到网页上写着 “Hello World”

二、事件驱动和回调:

上面的代码也可以如此编写:(即onRequest函数作为参数传递给 http.createServer() 

var http = require("http");
function onRequest(request, response) {
  console.log("Request received.");
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");

onRequest函数会在 http.createServer() 方法执行时的特定时间点去调用(即某个事件发生时,才会执行——事件驱动的回调

回调函数的目的: 当我们使用 http.createServer 方法的时候,我们当然不只是想要一个侦听某个端口的服务器,我们还想要它在服务器收到一个HTTP请求的时候做点什么

执行上面的代码(node server.js )终端会输出上图的  Server has started.  文本;

再打开 http://localhost:8888/  路径,终端会输出上图的 Request received. 文本,输出两次(因为还会访问一次http://localhost:8888/favicon.ico);

这就是事件驱动,访问时(事件发生)才会调用。

三、服务器相关:

1. onRequest函数被调用时,request 和 response 作为参数会被传入;

2. request 和 response 是对象,可以使用它们的方法来 处理HTTP请求的细节,也可以 响应请求 (即给发请求的浏览器返回数据);

3. 上面的代码:

收到请求时,

使用 response.writeHead() 函数发送一个HTTP状态(200)和HTTP头的内容类型(content-type),

使用 response.write() 函数在HTTP相应主体中发送文本“Hello World"。

调用 response.end() 完成响应。

 暂时未使用 request ,request中放的是请求时的携带的参数

四、node中模块的导入导出

//导入http模块,并使用
var http = require("http");
...
http.createServer(...).listen(8888);
//此处使用http变量来接受赋值,也可以使用其他变量


//导出自己的模块start,我们把它写在server.js中
function start() {
   ...   
}

exports.start = start;

//导入自己的模块start
var server = require("./server");

server.start();
原文地址:https://www.cnblogs.com/nangezi/p/10969152.html