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月前
|
JavaScript 前端开发 C语言
javascript基础入门
javascript基础入门
24 1
|
1月前
egg.js 24.3-24.5router路由相关
egg.js 24.3-24.5router路由相关
23 0
|
3天前
|
缓存 JavaScript 前端开发
Vue.js 路由时用于提高应用程序性能
Vue.js 路由时用于提高应用程序性能
|
12天前
|
JavaScript 前端开发 应用服务中间件
node.js之第一天学习
node.js之第一天学习
|
30天前
11_nest.js模块
11_nest.js模块
24 0
|
1月前
|
JavaScript
Node.js之http模块
Node.js之http模块
|
1月前
|
监控 JavaScript
vue.js路由
vue.js路由
33 0
vue.js路由
|
2月前
|
前端开发 JavaScript
从零开始学习前端开发:HTML、CSS、JavaScript入门指南
【2月更文挑战第1天】本文将带领读者从零开始学习前端开发,介绍HTML、CSS和JavaScript的基础知识与应用,帮助读者快速入门前端开发领域。
65 1
|
2月前
|
JSON 前端开发 JavaScript
Webpack【Webpack图片处理、Webpack中proxy代理 、自动清理dist、Webpack优化、JavaScript中的代码检查】(三)-全面详解(学习总结---从入门到深化)
Webpack【Webpack图片处理、Webpack中proxy代理 、自动清理dist、Webpack优化、JavaScript中的代码检查】(三)-全面详解(学习总结---从入门到深化)
35 0
Webpack【Webpack图片处理、Webpack中proxy代理 、自动清理dist、Webpack优化、JavaScript中的代码检查】(三)-全面详解(学习总结---从入门到深化)
|
2月前
|
资源调度 JavaScript 关系型数据库
Node.js【文件系统模块、路径模块 、连接 MySQL、nodemon、操作 MySQL】(三)-全面详解(学习总结---从入门到深化)
Node.js【文件系统模块、路径模块 、连接 MySQL、nodemon、操作 MySQL】(三)-全面详解(学习总结---从入门到深化)
33 0