Node.js 搭建Web服务器和Web客户端

网友投稿 479 2022-05-29

服务器定义

Web服务器一般指网站服务器,是指驻留于因特网上某种类型计算机的程序,Web服务器的基本功能就是提供Web信息浏览服务。它只需支持HTTP协议、HTML文档格式及URL,与客户端的网络浏览器配合。

目前最主流的三个Web服务器是Apache、Nginx、IIS。

Web 应用架构

1. Client - 客户端,一般指浏览器,浏览器可以通过 HTTP 协议向服务器请求数据。 2. Server - 服务端,一般指 Web 服务器,可以接收客户端请求,并向客户端发送响应数据。 3. Business - 业务层, 通过 Web 服务器处理应用程序,如与数据库交互,逻辑运算,调用外部程序等。 4. Data - 数据层,一般由数据库组成。

1

2

3

4

文档目录结构

代码实战

1、htmlDemo.js

var http = require('http'); var fs = require('fs'); var url = require('url'); var path = require('path'); http.createServer(function(request, response) { var pathname = url.parse(request.url).pathname; var readDir = path.join(__dirname, 'public'); //默认路径是命令行的路径,而不是js文件的路径 //不仅是html文件,所用到的资源(image、css、js等)都会在该函数被请求 //html里的图片不能访问到它的上一级目录 console.log('Request for pathname = ' + pathname); var subPathname = pathname.substr(1); if(!subPathname) { subPathname = 'index.html'; } if(!path.extname(subPathname)) { subPathname+='.html'; } console.log('after modify pathname = ' + subPathname); var readPath = path.join(readDir, subPathname); console.log(readPath); fs.readFile(readPath, function(err, data) { if(!err) { response.writeHead(200, {'Content-Type':'text/html'}); response.end(data); } else { console.log(err); response.writeHead(404, {'Content-Type':'text/html'}); fs.readFile(path.join(readDir, '404.html'), function(err, data) { if(err) { console.log(err); response.end(); } else { response.end(data); } }); } }); }).listen(8080); console.log('Server running at http://127.0.0.1:8080'); http.request({host:'localhost', port:'8080', path:'/index.html'}, function(response){ //注意这里必须先赋空值,否则会加入'undefined'字符串 var body = ''; //一直有数据,需要不断的更新 response.on('data', function(data){ //调用多少次response.write和end就会触发多少次on('data')事件 console.log('response.on data emitter'); body += data; }).on('end', function(){ console.log('response.on end emitter'); console.log(body); }); }).end();

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

2、index.html

Sample Page hello world!

1

2

3

4

5

6

7

8

3、404.html

404 File Not Found

1

2

3

4

5

6

7

8

运行截图

javaScript Node.js web前端

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:P40-前端基础-BFC解决浮动带来的高度塌陷问题
下一篇:PostgreSQL — 外键关联操作
相关文章

 发表评论

暂时没有评论,来抢沙发吧~