Node中的http模块

node与http模块

http模块实现简单的页面展示
const http=require('http')//注意:使用http模块需要先行引入
创建一个服务:
var server =http.createServer(function(req,res){
req=>resquest=>IncomingMessage类
res=>Response=>SeverResponse类
res.writeHead(200,{'ContentType':'text/html'})
ContentType由res返回文件扩展名决定

点击了解ContentType

写入html页面:
res.write(`<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
    div{
        height: 100px;
        width: 100px;
        background-color: red;
    }
    </style>
</head>
<body>
    <div class="d1">啊</div>
    <div class="d1">真</div>
    <div class="d1">好</div>
    <div class="d1">啊</div>
</body>
</html>`)
结束并监听
res.end()//不要在end后面再去修改你的请求
})
//http 默认80端口 https默认443端口
//域名可不填 计算机一般默认为 localhost 127.0.0.1
server.listen(3000)//server.listen(3000,域名)

http模块文本乱码处理
方法1:
const http = require('http')
var server = http.createServer(function(req,res){
res.writeHead(200,{"Content-type":"text/plain;charset=UTF-8"});//改变编译码(转中文)
res.write('你好啊!这是来自node的文本') //写身
res.end() //标志写完
})
server.listen(3000)
方法2:
const http = require('http')
var server = http.createServer(function(req,res){
res.setHeader("Content-Type","text/html;charset=UTF-8");//改变编译码(转中文)
res.end('你好啊!这是来自node的文本') //标志写完(未指定格式,此处乱码)
})
server.listen(3000)

http模块实现Html表单提交 a标签跳转 Ajax交互
Html页面代码(node5.html):
 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <a href="/txt?txtname=1">1111</a>
    <a href="/txt?txtname=2">2222</a>

    <!-- 网址返回http://www.baidu.com/s?wd=实现百度搜索功能 -->
    <form action="http://www.baidu.com/s">
        <input type="text" name="wd"> 
        <input type="submit" value="提交">
    </form>

    <!-- GET与node交互 -->
    <form action="/txt" method="GET">
        <input type="text" name="txtname">
        <input type="submit" value="提交">
    </form>

    <!-- POST与node交互 -->
    <form action="/login" method="POST">
        <input type="text" name="username">
        <input type="password" name="password">
        <input type="submit" value="提交">
    </form>

    <!-- Ajax与node交互 -->
    <script>
        var xhr=new XMLHttpRequest()
        xhr.open('POST','/login',true)//node中 req.url == '/login' 满足
        // 设置请求头
        xhr.setRequestHeader('Content-Type','text/json')

        // 传输数据需要用json格式
        xhr.send(JSON.stringify({username:'123',password:'789654'}))
        xhr.onreadystatechange=function(){
           
            if(xhr.status==200&&xhr.readyState==4){
                console.log(xhr.response)
            }

        }

    </script>
</body>
</html>
Node服务端代码:
const fs = require('fs')
const path = require('path')
const querystring = require('querystring')
const url = require('url')
const http = require('http')


var server = http.createServer(function (req, res) {
  if (req.method.toLowerCase() == 'get') { //toLowerCase转为小写
      // console.log(req.url)
      if (req.url == '/') { //进入Html页面
          fs.readFile('./node5.html', { encoding: 'utf-8' }, function (err, data) {
              if (err && err.code == 'ENOENT') {
                  res.writeHead(404)
                  res.write('404 NOT FOUND')
                  res.end()
              }
              res.writeHead(200, { 'Content-Type': 'text/html' })
              res.write(data)
              res.end()
          })
      }
      //对于url解析为对象
      var urlParseObj = url.parse(req.url)
      //获取url对象的pathname
      var pathname_my = urlParseObj.pathname
      //读取url对象的查询语句
      var query_my = urlParseObj.query
      //将查询语句解析为对象
      var queryParseObj = querystring.parse(query_my)
      // 获取想要请求文件的名字
      var txtname = queryParseObj.txtname
      // 拼接访问文件路径
      var lj = path.join('./', txtname   '.txt')
      // console.log(lj)
      if (pathname_my == '/txt') { //a标签的文件跳转
          fs.readFile(lj, { encoding: 'utf-8' }, function (err, data) {
              if (err && err.code == 'ENOENT') {
                  res.writeHead(404)
                  res.write('404 NOT FOUND')
                  res.end()
              }
              res.setHeader("Content-Type", "text/html;charset=UTF-8");//改变编译码(转中文)
              // res.writeHead(200,{'Content-Type':'text/plain'})
              // console.log(data)
              res.write(data)
              res.end()
          })

      }
  }

  if (req.method.toLowerCase() == 'post') { //POST请求Ajax与表单提交
      // console.log(req.url)
      if (req.url == '/login') {
          var data = ''
          req.on('data', function (chunk) {
              console.log(chunk)//将内容返回为16进制码
              console.log(chunk.toString())//16进制码转为字符串
              data  = chunk.toString()//将数据存入data
          })
          req.on('end', function () {
              console.log('请求完成', data)
              var resultObjName
              // 判断是否是请求的json文件
              console.log(req.headers)
              if (req.headers['content-type'] == 'text/json') {//Ajax中 'content-type':'text/json' 反之'content-type': 'application/x-www-form-urlencoded'
                  // 对于json文件进行解析
                  console.log('这是Ajax数据' data)
                  resultObjName = JSON.parse(data).username
                  console.log('Ajax and JSON运行')
              } 
              else {
                  resultObjName = querystring.parse(data).username
              }
              console.log('已运行' resultObjName)
              res.setHeader("Content-Type", "text/html;charset=UTF-8");//改变编译码(转中文)
              // res.writeHead(200)
              res.write(resultObjName)
              res.end()
          })

      }
  }
})
server.listen(3000)

Http实现前台CSS JS JPG GIF引入
Html页面代码(index.html):
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Document</title>
   <link rel="icon" href="./index.ico">
   <link rel="stylesheet" href="./index.css">
</head>
<body>
   <div class="cheng">成功</div>
   <img src="./index.jpg" alt="">
   <img src="./index.gif" alt="">
   <script src="./index.js"></script>
</body>
</html>
Node服务端代码:
const http = require('http')
const fs=require('fs')
var server = http.createServer(function (req,res) {
   if(req.method.toLowerCase()=="get"){//toLowerCase()方法用于把字符串转换为小写。
       console.log(req.method)//此时返回GET
       console.log(req.url)
       if (req.url == '/') {//主页面
           fs.readFile('./index.html',{encoding:'utf-8'},function(err,data){
              res.writeHead(200, { 'Content-Type': 'text/html' })
              res.write(data)
              res.end() 
           }) 
       }
       if(req.url=='/index.css'){
           fs.readFile('./index.css',{encoding:'utf-8'},function(err,data){
               res.writeHead(200, { 'Content-Type': 'text/css' })//此编码根据类型变化
               res.write(data)
               res.end() 
            }) 
       }
       if(req.url=='/index.js'){
           fs.readFile('./index.js',{encoding:'utf-8'},function(err,data){
               res.writeHead(200, { 'Content-Type': 'application/x-javascript' })//此编码根据类型变化
               res.write(data)
               res.end() 
            }) 
       }
       if(req.url=='/index.jpg'){
           fs.readFile('./index.jpg',function(err,data){//不可含有{encoding:'utf-8'}
               res.writeHead(200, { 'Content-Type': 'image/jpeg' })//此编码根据类型变化
               res.write(data)
               res.end() 
            }) 
       }
       if(req.url=='/index.gif'){
           fs.readFile('./index.gif',function(err,data){//不可含有{encoding:'utf-8'}
               res.writeHead(200, { 'Content-Type': 'image/gif' })//此编码根据类型变化
               res.write(data)
               res.end() 
            }) 
       }

   }
})
server.listen(3000)
Node服务端代码(升级):
const http = require('http')
const fs = require('fs')
const path = require('path')

const mime = require('./mime')
const static = './'

var sever = http.createServer(function (req, res) {
  if (req.method.toLowerCase() == 'get') {//req.method此时为GET toLowerCase()方法用于把字符串转换为小写。
      console.log(req.url)
      if (req.url == '/') {
          fs.readFile('./index.html', { encoding: 'utf-8' }, function (err, data) {
              res.writeHead(200, { 'Content-Type': 'text/html' })
              res.write(data)
              res.end()
          })
      }
      if (req.url.indexOf('.') > -1) {
          var lj = path.join(static, req.url)
          console.log(lj)
          fs.readFile(lj, function (err, data) {
              // console.log(err,err.code)
              // if (err && err.code == 'ENOENT') {
                  console.log('运行')
                  res.writeHead(200, { 'Content-Type': mime.JudgeType(req.url) })
                  res.write(data)
                  res.end()
              // }
          })
      }
  }
})
sever.listen(3000)
Node服务端代码(升级)mime文件:
const path=require('path')
var JudgeType=function(filename){
  var ext=path.parse(filename).ext
  switch(ext){
      case'.html':
            return 'text/html'
      case'.css':
            return 'text/css'
      case'.js':
            return 'application/x-javascript'  
      case'.png':
            return 'image/png'
      case'.jpg':
            return 'image/jpeg'    
      case'.gif':
            return 'image/gif'   
      case'.ico':
            return 'image/x-icon'                
  }
}
exports.JudgeType=JudgeType

Http解决跨域问题及范例
const http = require('http')
var server = http.createServer(function (req, res){
  if (req.method.toLowerCase() == 'get') {
      console.log(req.url)
      if (req.url == '/') {
   
              res.setHeader('Access-Control-Allow-Origin','*')//跨域问题解决
              res.writeHead(200, { 'Content-Type': 'text/html' })
              res.write('456')
              res.end()
        
      }
  }
})
server.listen(3000)


http模块用GET POST方法实现登录验证
Html首页代码(node6(login).htm):
<!DOCTYPE html>
<html lang="en">

<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Document</title>
</head>

<body>
   <!-- 默认get -->
   <form action="/login">
       <input type="text" name="username">
       <input type="password" name="password">
       <button>点我</button><span>此方法进入网址会显示出数据(GET)</span>
   </form>
   <br>
   <form action="/login" method="POST">
       <input type="text" name="username">
       <input type="password" name="password">
       <button>点我</button><span>此方法进入看不到输入数据(POST)</span>
   </form>
</body>

</html>
Html登录成功页面代码(node6().htm):
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Document</title>
</head>
<body>
   成功进入
</body>
</html>
Node服务端代码:
const http = require('http')
const fs = require('fs')
const url = require('url')
const querystring = require('querystring')
var server = http.createServer(function (req, res) {
   if (req.method.toLowerCase() == 'get') {//get 数据存在url中
       // console.log(req.url)
       if (req.url == '/') {
           fs.readFile('./node6(login).htm', { encoding: 'utf-8' }, function (err, data) {
               if (err && err.code == 'ENOENT') {
                   res.writeHead(403)
                   res.write('403 FORBIDDEN')
                   res.end()
               }
               res.writeHead(200, { 'Content-Type': 'text/html' })
               res.write(data)
               res.end()
           })
       }
       console.log(req.url)
       // console.log(url.parse(req.url).pathname)
       var urlObj = url.parse(req.url)
       var pathname = urlObj.pathname
       var queryObj = querystring.parse(urlObj.query)
       if (pathname == '/login') {//接口传参
           if (queryObj.username == '昵称' && queryObj.password == '密码') {

               fs.readFile('./node6().htm', { encoding: 'utf-8' }, function (err, data) {
                   if (err && err.code == 'ENOENT') {
                       res.writeHead(404)
                       res.write('404 NOT FOUND')
                       res.end()
                   }
                   res.writeHead(200, { 'Content-Type': 'text/html' })
                   res.write(data)
                   res.end()
               })
           }
           else {
               res.setHeader("Content-Type", "text/html;charset=UTF-8")
               res.write('密码错误')
               res.end()
           }
       }
   }
   if (req.method.toLowerCase() == 'post') {//post 数据在data中
       if (req.url == '/login') {
           var data = ''
           req.on('data', function (chunk) {
               data  = chunk.toString()//16进制转字符
           })
           req.on('end', function () {
               console.log(data)
               var queryObj = querystring.parse(data)
               if (queryObj.username == '昵称' && queryObj.password == '密码') {
                   fs.readFile('./node6().htm', { encoding: 'utf-8' }, function (err, data) {
                       if (err && err.code == 'ENOENT') {
                           res.writeHead(404)
                           res.write('404 NOT FOUND')
                           res.end()
                       }
                       res.writeHead(200, { 'Content-Type': 'text/html' })
                       res.write(data)
                       res.end()
                   })
               }
               else {
                   res.setHeader("Content-Type", "text/html;charset=UTF-8")
                   res.write('密码错误')
                   res.end()
               }
           })
       }
   }
})
server.listen(3000)

Http模块中的Cookie
const http=require('http')
const fs =require('fs')
const querystring=require('querystring')
//cookie设置多个时,用[],中间用逗号隔开
var server=http.createServer(function (req, res) {
if(req.method.toLowerCase()=='get'){
  if(req.url=='/'){
      fs.readFile('./node6(login).htm',{encoding:'utf-8'},function(err,data){
        if(err&&err.code=='ENOENT'){
            res.writeHead(403)
            res.write('403 FORBIDDEN')
            res.end()
        }
        res.writeHead(200,{'Content-type':'text/html'})
        res.write(data)
        res.end()
      })
  }
  if(req.url=='/index'){
      fs.readFile('./node6().htm',{encoding:'utf-8'},function(err,data){
          res.writeHead(200,{'Content-type':'text/html'})
          res.write(data)
          res.end()
      })
  }

}
if(req.method.toLowerCase()=='post'){//我们一般只有Ajax和form表单会发起post请求
  if(req.url=='/login'){
      var data=''
      req.on('data',function(shuju){
          data =shuju.toString()
      })
      req.on('end',function(){
          var queryObj=querystring.parse(data)
          // console.log(queryObj)
          if(queryObj.username=='admin'&&queryObj.password=='123'){
              res.setHeader('Set-cookie',['username=' queryObj.username '; ','password=' queryObj.password])//向页面存储Cookie,且页面请求头将含有Cookie便于认证
              // res.setHeader('Set-cookie','username=' queryObj.username '; ')
              // res.setHeader('Set-cookie','password=' queryObj.password)
              res.writeHead(302,{Location:'/index'})//浏览器 的请求是get请求
              res.end()
          }
          else{
              res.writeHead(403)
              res.write('403 FORBIDDEN')
              res.end()
          }
      })
  }
}
})
server.listen(3000)

Http模块重定向及范例
const http = require('http')
var server = http.createServer(function (req, res) {

      console.log(req.url)
      if (req.url == '/kanshipin') {
         
              res.writeHead(302, { Location:'http://www.bilibili.com' }) 
              res.write()
              res.end()
         
      }   
})
server.listen(3006)

Http模块实现爬虫
const https = require('https')
const fs=require('fs')
//https://ii.hywly.com/a/1/22523/1.jpg
//'/a/1/22523/1.jpg'
var patupian=function(i){
var request=https.request({
  protocol:'https:',
  host:'ii.hywly.com',
  port:443,
  method:'get',
  path:'/a/1/22523/' i '.jpg',
  headers:{//request headers 加密可用
//'Referer':'.....'
//'User-Agent':'.....'
  }
})
request.on('response',function(res){
  var arr=[]
  res.on('data',function(chunk){
      console.log(chunk)//图片得到的是Buffer 16进制
      arr.push(chunk)
  })
  res.on('end',function(){
        console.log(arr)
        fs.writeFile('./爬虫图片/' i '.jpg',Buffer.concat(arr),function(){
            console.log('图片写入成功')
        })//没有则创建一个
  })
})
request.end()
}
for(var i=1;i<27;i  ){
patupian(i)
}
--End--
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Node-RED是一个开源的、基于JavaScript的可视化编程工具,用于创建物联网(IoT)和自动化工作流。它使用Node.js运行,允许用户通过拖放节点(nodes)来构建简单的流程,这些节点代表了各种功能,如读取传感器数据、执行HTTP请求、发送消息等。 在Node-RED,安装模块(也称为“nodes”或插件)是扩展其功能的关键。它们提供了对特定设备、服务或API的支持。要安装Node-RED模块,你需要执行以下几个步骤: 1. **打开Node-RED**: 打开你的浏览器,访问`http://localhost:1880`,如果你的Node-RED已经配置为默认启动。 2. **登录控制台**: 登录到你的Node-RED实例(通常不需要用户名和密码,直接进入)。 3. **前往管理界面**: 点击右上角的齿轮图标(或“ Manage”按钮),进入管理页面。 4. **找到“Nodes”选项**: 在管理菜单,选择“Manage”或“Nodes”,这将带你到一个包含已安装和可用节点的列表。 5. **搜索或浏览模块**: 在这个页面,你可以通过搜索框查找你想要安装的模块名,或者浏览分类浏览。 6. **安装模块**: 点击你找到的模块,然后点击“Install”按钮进行安装。可能需要确认权限或等待安装过程完成。 7. **刷新页面**: 安装完成后,记得重新加载或刷新Node-RED页面,新安装的模块才会出现在可用节点库。 **相关问题--:** 1. Node-RED支持哪些类型的模块? 2. 如何查看已安装的Node-RED模块? 3. 安装错误时如何解决?

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值