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("程序执行完毕。");
目录
相关文章
|
19天前
HTTP协议中请求方式GET 与 POST 什么区别 ?
GET和POST的主要区别在于参数传递方式、安全性和应用场景。GET通过URL传递参数,长度受限且安全性较低,适合获取数据;而POST通过请求体传递参数,安全性更高,适合提交数据。
247 2
|
3月前
|
JavaScript 前端开发 API
Node.js中发起HTTP请求的五种方式
以上五种方式,尽管只是冰山一角,但已经足以让编写Node.js HTTP请求的你,在连接世界的舞台上演奏出华丽的乐章。从原生的 `http`到现代的 `fetch`,每种方式都有独特的风格和表现力,让你的代码随着项目的节奏自由地舞动。
373 65
|
2月前
|
Go 定位技术
Golang中设置HTTP请求代理的策略
在实际应用中,可能还需要处理代理服务器的连接稳定性、响应时间、以及错误处理等。因此,建议在使用代理时增加适当的错误重试机制,以确保网络请求的健壮性。此外,由于网络编程涉及的细节较多,彻底测试以确认代理配置符合预期的行为也是十分重要的。
108 8
|
1月前
|
JSON JavaScript API
Python模拟HTTP请求实现APP自动签到
Python模拟HTTP请求实现APP自动签到
|
2月前
|
缓存
|
1月前
|
数据采集 JSON Go
Go语言实战案例:实现HTTP客户端请求并解析响应
本文是 Go 网络与并发实战系列的第 2 篇,详细介绍如何使用 Go 构建 HTTP 客户端,涵盖请求发送、响应解析、错误处理、Header 与 Body 提取等流程,并通过实战代码演示如何并发请求多个 URL,适合希望掌握 Go 网络编程基础的开发者。
|
2月前
|
缓存 JavaScript 前端开发
Vue 3 HTTP请求封装导致响应结果无法在浏览器中获取,尽管实际请求已成功。
通过逐项检查和调试,最终可以定位问题所在,修复后便能正常在浏览器中获取响应结果。
143 0
|
2月前
|
Go
如何在Go语言的HTTP请求中设置使用代理服务器
当使用特定的代理时,在某些情况下可能需要认证信息,认证信息可以在代理URL中提供,格式通常是:
196 0
|
4月前
|
Go
在golang中发起http请求以获取访问域名的ip地址实例(使用net, httptrace库)
这只是追踪我们的行程的简单方法,不过希望你跟着探险家的脚步,即使是在互联网的隧道中,也可以找到你想去的地方。接下来就是你的探险之旅了,祝你好运!
161 26
|
5月前
|
JSON API 数据安全/隐私保护
使用curl命令在服务器上执行HTTP请求
总的来说,curl是一个非常强大的工具,它可以让你在命令行中发送各种类型的HTTP请求。通过学习和实践,你可以掌握这个工具,使你的工作更加高效。
365 30

热门文章

最新文章