Maison > interface Web > js tutoriel > le corps du texte

Comment créer des serveurs Web et TCP dans Node.js

亚连
Libérer: 2018-06-22 16:33:37
original
1143 Les gens l'ont consulté

这篇文章主要介绍了用Node.js创建Web服务器和TCP服务器的方法和处理技巧,需要的读者们学习一下吧。

使用http模块创建Web服务器

Web服务器的功能:

接受HTTP请求(GET、POST、DELETE、PUT、PATCH)

处理HTTP请求(自己处理,或请求别的程序处理)

做出响应(返回页面、文件、各类数据等)

常见的Web服务器架构:

Nginx、Apache:负责接受HTTP请求,确定谁来处理请求,并返回请求的结果

php-fpm / php模块:处理分配给自己的请求,并将处理结果返回给分配者

常见请求种类:

请求文件:包括静态文件(网页、图片、前端JavaScript文件、css文件...),及由程序处理得到的文件

完成特定的操作:如登录、获取特定数据等

Node.js的Web服务器:

不依赖其他特定的Web服务器软件(如Apache、Nginx、IIS......)

Node.js代码处理请求的逻辑

Node.js代码负责Web服务器的各种“配置”

使用Express创建Web服务器

简单的Express服务器

静态文件服务

路由

中间件

简单的Express服务器:

var express = require('express'); 
var app = express(); 
app.get('', function(req, res){ 
<span style="white-space:pre"> </span>res.end(&#39;hello\n&#39;); 
<span style="white-space:pre"> </span>}); 
<span style="white-space:pre"> </span>app.listen(18001, function afterListen(){ 
<span style="white-space:pre"> </span>console.log(&#39;express running on http://localhost:18001&#39;); 
<span style="white-space:pre"> </span>});
Copier après la connexion

静态文件范围:

网页、纯文本、图片、前端JavaScript代码、CSS样式表文件、媒体文件、字体文件

使用Express访问静态文件

<span style="white-space:pre"></span>app.use(express.static(&#39;./public&#39;));
Copier après la connexion

路由:

将不同的请求,分配给相应的处理函数

区分:路径、请求方法

三种路由实现方法:

path:比较简单

Router:比较适合同一个路由下的多个子路由

route:比较适合API

中间件

Connect:Node.js的中间件框架

分层处理

每层实现一个功能

创建TCP服务器

使用net模块创建TCP服务器

使用telnet连接TCP服务器

使用net创建TCP客户端

利用node.js搭建简单web服务器JS代码部分:

var http = require(&#39;http&#39;);
var url = require(&#39;url&#39;);
var path = require(&#39;path&#39;);
var fs = require(&#39;fs&#39;);
var dir, arg = process.argv[2] || &#39;&#39;; // 命令行第三个参数,用来接收目录,可为空,相对当前server.js文件的目录名称
// 比如使用命令 node server debug,意思就是debug文件夹与server.js文件同级
// 且你想以debug文件夹启动web服务
 
http.createServer(function (req, res) {
var pathname = __dirname + url.parse(req.url).pathname;
dir = dir ? dir : pathname; // 记住dir(目录)
pathname = dir ? pathname.replace(dir, dir + arg + &#39;/&#39;) : pathname; // 替换文件静态路径
if (path.extname(pathname) == "") {
pathname += "/";
}
if (pathname.charAt(pathname.length - 1) == "/") {
pathname += "index.html"; // 入口文件,此处默认index.html
}
 
fs.exists(pathname, function (exists) {
if (exists) {
switch (path.extname(pathname)) {
case ".html":
res.writeHead(200, {"Content-Type": "text/html"});
break;
case ".js":
res.writeHead(200, {"Content-Type": "text/javascript"});
break;
case ".css":
res.writeHead(200, {"Content-Type": "text/css"});
break;
case ".gif":
res.writeHead(200, {"Content-Type": "image/gif"});
break;
case ".jpg":
res.writeHead(200, {"Content-Type": "image/jpeg"});
break;
case ".png":
res.writeHead(200, {"Content-Type": "image/png"});
break;
default:
res.writeHead(200, {"Content-Type": "application/octet-stream"});
} 
// res可以自己添加信息来简单交互 比如可以修改点header信息 或者修改返回的资源数据
fs.readFile(pathname, function (err, data) {
res.end(data);
});
}
else {
res.writeHead(404, {"Content-Type": "text/html"});
res.end("<h1>404 Not Found</h1>");
}
});
}).listen(8085, "127.0.0.5"); // 服务器端口
console.log("server running at http://127.0.0.5:8085/");
Copier après la connexion

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

在laydate.js中加载路径出现错误

在vue-router中如何实现路由传参

使用jQuery操作table如何实现单元格合并

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!