Node.js【GET/POST请求、http模块、路由、创建客户端、作为中间层、文件系统模块】(二)-全面详解(学习总结---从入门到深化)

简介: Node.js【GET/POST请求、http模块、路由、创建客户端、作为中间层、文件系统模块】(二)-全面详解(学习总结---从入门到深化)



 

Node.js Stream(流)(三)

1、管道流

管道提供了一个数据从输出流到输入流的机制。

我们使用管道可以从一个流中获取数据并将数据传递到另外一个流中。

举例:复制文件

我们把文件比作装水的桶,而水就是文件里的内容,我们用一根管子 (pipe) 连接两个桶使得水从一个桶流入另一个桶,这样就慢慢的实现了大文件的复制过程。

 

var fs = require("fs");
// 创建一个可读流
var readerStream = fs.createReadStream('input.txt');
// 创建一个可写流
var writerStream = fs.createWriteStream('output.txt');
// 管道读写操作
// 读取 input.txt 文件内容,并将内容写入到output.txt 文件中
readerStream.pipe(writerStream);

2、链式流

链式是通过连接输出流到另外一个流并创建多个流操作链的机制。

pipe() 方法的返回值是目标流。

var fs = require("fs");
var zlib = require('zlib');
// 压缩 input.txt 文件为 input.txt.gz
fs.createReadStream('input.txt').pipe(zlib.createGzip()).pipe(fs.createWriteStream('input.txt.gz')
);
var fs = require("fs");
var zlib = require('zlib');
// 解压 input.txt.gz 文件为 input.txt
fs.createReadStream('input.txt.gz').pipe(zlib.createGunzip()).pipe(fs.createWriteStream('input.txt'));

Node.js http模块

HTTP 核心模块是 Node.js 网络的关键模块。

使用该模块可以创建web服务器。

1、引入http模块

const http = require('http')

2、创建 Web 服务器

//返回 http.Server 类的新实例
//req是个可读流
//res是个可写流
const server=http.createServer( function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
  res.write('服务器响应了,这是响应内容')
  res.end()
})

3、启动服务器并监听某个端口

server.listen('3030',function(){
    console.log('服务器已做好准备,正在监听3030端口')
})

Node.js GET/POST请求(一)

1、获取 POST 请求内容

<!-- test.html -->
<form id="form1" action="http://localhost:3030" method="post">
   姓名:<input type="text" name="name"><br />
   年龄:<input type="text" name="age"><br />
    <input type="submit" value="提交"
/>
</form>
//test.js
const http=require('http')
const querystring = require('querystring')
const server = http.createServer((req, res) => {
  var bodyStr = ''
    req.on('data', function (chunk) {
       bodyStr += chunk
 })
  req.on('end', function () {
   const body = querystring.parse(bodyStr);
   // 设置响应头部信息及编码
   res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
    if(body.name && body.age) {
      res.write("姓名:" + body.name);
      res.write("<br>");
      res.write("年龄:" + body.age);
   }
    res.end()
 });
})
server.listen('3030',function(){
  console.log('服务器正在监听3030端口')
})

Node.js GET/POST请求(二)

1、获取Get请求内容

//浏览器访问地址
http://localhost:3030/?name=%27baizhan%27&&age=10
const http = require('http')
const url = require('url')
const server = http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
  //使用url.parse将路径里的参数解析出来
  const { query = {} } = url.parse(req.url, true)
  for ([key, value] of Object.entries(query)) {
    res.write(key + ':' + value)
 }
  res.end();
})
server.listen('3030', function () {
  console.log('服务器正在监听3030端口')
})

Node.js 路由

我们要为路由提供请求的URL和其他需要的GET及POST参数,随后路由需要根据这些数据来执行相应的代码。

const http = require('http')
const url = require('url')
const server = http.createServer(function (req, res) {
  //获取请求路径
  const pathname = url.parse(req.url).pathname;
  if (pathname == '/') {
    res.end('hello')
 }else if (pathname == '/getList') {
    res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
    res.write(JSON.stringify({ recrods: [{ name: 'fyx' }] }))
    res.end()
 }else{
    res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
    res.end('默认值')
 }
})
server.listen('3030', function () {
  console.log('服务器正在监听3030端口')
})

整理

//router.js
module.exports=(pathname,res)=>{
  if (pathname == '/') {
    res.end('hello')
 }else if (pathname == '/getList') {
    res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
    res.write(JSON.stringify({ recrods: [{ name: 'fyx' }] }))
    res.end()
 }else{
    res.end('默认值')
 }
}
//test.js
const http = require('http')
const url = require('url')
const router = require('./router')
const server = http.createServer(function (req, res) {
  const pathname = url.parse(req.url).pathname;
  router(pathname,res)
})
server.listen('3030', function () {
  console.log('服务器正在监听3030端口')
})

Node.js 创建客户端

//client.js
var http = require('http');
// 用于请求的选项
var options = {
     host: 'localhost',
     port: '3030',
     path: '/' 
};
// 处理响应的回调函数
var callback = function(response){
 // 不断更新数据
 var body = '';
 response.on('data', function(data) {
   body += data;
 });
 response.on('end', function() {
   // 数据接收完成
   console.log(body);
 });
}
// 向服务端发送请求
var req = http.request(options, callback);
req.end();
//server.js
const http=require('http')
const url=require('url')
const server = http.createServer(function (req, res) {
  const {pathname}=url.parse(req.url)
  if (pathname == '/') {
    res.write('hello')
 res.write('xiaotong')
 res.end()
 }
})
server.listen('3030', function () {
  console.log('服务器正在监听3030端口')
})

 

Node.js 作为中间层

//test.js
const http = require('http')
const url = require('url')
const server = http.createServer(function (req, res) {
  const pathname = url.parse(req.url).pathname;
  // 用于请求的选项
  var options = {
    host: 'localhost',
    port: '8080',
    path: pathname,
    method:req.method,
    headers:{token:'xxxxx'}
 };
  // 处理响应的回调函数
  var callback = function (response) {
    const {headers= {},statusCode}=response
    res.writeHead(statusCode, {...headers})
    response.pipe(res)
 }
  // 向服务端发送请求
  var req = http.request(options, callback);
  req.end();
})
server.listen('3030', function () {
  console.log('服务器正在监听3030端口')
})

 

//server.js
const http=require('http')
const server=http.createServer((req,res)=>{
  const {headers={}}=req
  res.writeHead(200,{'Content-Type': 'application/json; charset=utf-8'})
  if(headers.token){
      res.end(JSON.stringify({code:0,message:'成功',data:[]}))
 }else{
     res.end(JSON.stringify({code:-1,message:'您还没有权限'}))
 }
})
server.listen('8080',function(){
  console.log('服务器正在监听8080端口')
})

Node.js 文件系统模块(一)

fs 模块提供了许多非常实用的函数来访问文件系统并与文件系统进行交互。

文件系统(fs 模块)模块中的方法均有异步和同步版本,例如读取文件内容的函数有异步的 fs.readFile() 和同步的 fs.readFileSync() 。

var fs = require("fs");
// 异步读取
fs.readFile('input.txt', function (err, data) {
 if (err) {
   return console.error(err);
 }
 console.log("异步读取: " + data.toString());
});
// 同步读取
var data = fs.readFileSync('input.txt');
console.log("同步读取: " + data.toString());
console.log("程序执行完毕。");
目录
相关文章
|
6月前
|
JSON 监控 API
掌握使用 requests 库发送各种 HTTP 请求和处理 API 响应
本课程全面讲解了使用 Python 的 requests 库进行 API 请求与响应处理,内容涵盖环境搭建、GET 与 POST 请求、参数传递、错误处理、请求头设置及实战项目开发。通过实例教学,学员可掌握基础到高级技巧,并完成天气查询应用等实际项目,适合初学者快速上手网络编程与 API 调用。
655 130
|
7月前
HTTP协议中请求方式GET 与 POST 什么区别 ?
GET和POST的主要区别在于参数传递方式、安全性和应用场景。GET通过URL传递参数,长度受限且安全性较低,适合获取数据;而POST通过请求体传递参数,安全性更高,适合提交数据。
684 2
|
7月前
|
JSON JavaScript API
Python模拟HTTP请求实现APP自动签到
Python模拟HTTP请求实现APP自动签到
|
7月前
|
数据采集 JSON Go
Go语言实战案例:实现HTTP客户端请求并解析响应
本文是 Go 网络与并发实战系列的第 2 篇,详细介绍如何使用 Go 构建 HTTP 客户端,涵盖请求发送、响应解析、错误处理、Header 与 Body 提取等流程,并通过实战代码演示如何并发请求多个 URL,适合希望掌握 Go 网络编程基础的开发者。
|
Web App开发
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
TCP洪水攻击(SYN Flood)的诊断和处理 Posted by  海涛  on 2013 年 7 月 11 日 Tweet1 ​1. SYN Flood介绍 前段时间网站被攻击多次,其中最猛烈的就是TCP洪水攻击,即SYN Flood。
1200 0
|
Web App开发 前端开发 Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
ZooKeeper 保证了数据的强一致性,  zk集群中任意节点(一个zkServer)上的相同znode下的数据一定是相同的。
919 0
|
Web App开发 前端开发
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
zookeeper watch的定义如下:watch事件是一次性触发器,当watch监视的数据发生变化时,通知设置了该watch的client,即watcher。
1137 0
|
Web App开发 前端开发 Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
Changing Hive Dynamic Partition Limits Symptoms: Hive enforces limits on the number of dynamic partitions that it creates.
1119 0
|
Web App开发 前端开发 Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
org.apache.hadoop.hive.ql.metadata.HiveException: Unable to rename output from: hdfs://nameservice/user/hive/warehouse/om_dw.
847 0
|
Web App开发 前端开发 算法
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
大数据风控指标介绍 2016-03-24 大林 1查准率与查全率 先说个例子,申请人有400个,其中有160个是好人,240个是坏人。
827 0