Node.js-web模块

 

创建web服务器

http模块主要用于HTTP服务端和客户端,使用HTTP服务端和客户端的功能,则必须调用http模块

 

最基本HTTP服务器架构

在和js文件同目录创建index.html文件(具体内容就不解释了,我写的html如下)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>s8要凉了</title>
</head>
<body>
<h1 style="text-align: center;vertical-align: middle">s9,你会等吗?</h1>
<h1 style="text-align: center;vertical-align: middle"></h1>
</body>
</html>

 

实例:

var http = require('http');
var
fs = require('fs');
var
url = require('url');


http.createServer( function (request, response) {
    var pathname = url.parse(request.url).pathname;

    console.log("Request for " + pathname + " received.");

    fs.readFile(pathname.substr(1), function (err, data) {
        if (err) {
            console.log(err);
           
// HTTP 状态码: 404 : NOT FOUND
            // Content Type: text/plain
           
response.writeHead(404, {'Content-Type': 'text/html'});
       
}else{
            // HTTP 状态码: 200 : OK
            // Content Type: text/plain
           
response.writeHead(200, {'Content-Type': 'text/html'});

           
// 响应文件内容
           
response.write(data.toString());
       
}

        response.end();
   
});
}).listen(6600);

// 控制台会输出以下信息
console.log('Server running at http://127.0.0.1:6600 /');

解析pathname这个参数,实质是查询是否有该页面存在,如果存在,读取页面数据,返回给客户端,如果不存在,则返回404报错。

输入的url为:localhost:6600/index.html

返回结果,即html文件。

 

运行结果:

也就是我刚才写的index.html页面,以上代码简单实现服务器端的功能。

 

 

创建web客户端

var http = require('http');

var
options = {
  host: ' localhost ',
 
port: '6600',
 
path:'/index.html',
};

var
callback = function () {
  var body = '';
 
response.on('data',function (data) {
      body+=data;
 
})

  response.on('end',function () {
      console.log(body);
 
})
};

var
req = http.request(options,callback());
req.end();

 

解析:

作为客户端,想服务器端发送请求。

通过http.request进行请求的发送

参数:

host:地址

port:端口号

path:网页名(如:index.html)

 

回调函数有一个参数,处理回调函数,当发送请求时被接收到,会触发data事件,当数据接收完成时,会触发end事件,表示发送请求结束。

req.end()结束请求数据传输

 

node.js创建服务器和npm基本操作

REPL和回调函数

node.js——绑定事件

node.js——error事件、缓冲区操作​​​​​​​

node.js——缓冲区操作

node.js——流的操作

node.js——模块系统和函数​​​​​​​

node.js——路由​​​​​​​

node.js——全局对象​​​​​​​

node.js对文件的操作​​​​​​​

node.js——web模块

 

猜你喜欢

转载自blog.csdn.net/xxtnt/article/details/83246581