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

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

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


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("程序执行完毕。");
目录
相关文章
|
1月前
|
算法 测试技术 C语言
深入理解HTTP/2:nghttp2库源码解析及客户端实现示例
通过解析nghttp2库的源码和实现一个简单的HTTP/2客户端示例,本文详细介绍了HTTP/2的关键特性和nghttp2的核心实现。了解这些内容可以帮助开发者更好地理解HTTP/2协议,提高Web应用的性能和用户体验。对于实际开发中的应用,可以根据需要进一步优化和扩展代码,以满足具体需求。
160 29
|
4月前
|
前端开发 API 开发者
Next.js 实战 (五):添加路由 Transition 过渡效果和 Loading 动画
这篇文章介绍了Framer Motion,一个为React设计的动画库,提供了声明式API处理动画和页面转换,适合创建响应式用户界面。文章包括首屏加载动画、路由加载Loading、路由进场和退场动画等主题,并提供了使用Framer Motion和next.js实现这些动画的示例代码。最后,文章总结了这些效果,并邀请读者探讨更好的实现方案。
117 7
|
6月前
|
缓存 JavaScript 安全
nodejs里面的http模块介绍和使用
综上所述,Node.js的http模块是构建Web服务的基础,其灵活性和强大功能,结合Node.js异步非阻塞的特点,为现代Web应用开发提供了坚实的基础。
181 62
|
5月前
|
缓存 前端开发 JavaScript
JavaScript前端路由的实现原理及其在单页应用中的重要性,涵盖前端路由概念、基本原理、常见实现方式
本文深入解析了JavaScript前端路由的实现原理及其在单页应用中的重要性,涵盖前端路由概念、基本原理、常见实现方式(Hash路由和History路由)、优点及挑战,并通过实际案例分析,帮助开发者更好地理解和应用这一关键技术,提升用户体验。
194 1
|
6月前
|
JavaScript
Node.js GET/POST请求
10月更文挑战第6天
63 2
Node.js GET/POST请求
|
6月前
|
JavaScript
Node.js 路由
10月更文挑战第5天
61 2
|
6月前
|
缓存 JSON JavaScript
Node.js模块系统
10月更文挑战第4天
73 2
|
6月前
|
JavaScript 应用服务中间件 Apache
Node.js Web 模块
10月更文挑战第7天
59 0
|
6月前
|
JavaScript 网络协议
Node.js 工具模块
10月更文挑战第7天
53 0
|
6月前
|
JavaScript 前端开发 应用服务中间件
Node.js Web 模块
Node.js Web 模块