• 【Node.js】http 模块


    1. http 模块

    import http from 'http'
    // 创建本地服务器接收数据
    const server = http.createServer((req, res) => {
      console.log(req.url)
      res.writeHead(200, { 
        'Content-Type': 'application/json' 
        // 'Content-Type': 'text/html;charset=utf-8'  // 将内容以 html 标签和 utf-8 的形式展示到网页上 
      })
      // write 中的内容直接展示到网页上
      // res.write('hello')
      res.end(JSON.stringify({
        data: "hello"
      }))
    })
    server.listen(8000,()=> {
      console.log("server is running")
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    /**
     * 目标:基于 http 模块创建 Web 服务程序
     *  1.1 加载 http 模块,创建 Web 服务对象
     *  1.2 监听 request 请求事件,设置响应头和响应体
     *  1.3 配置端口号并启动 Web 服务
     *  1.4 浏览器请求(http://localhost:3000)测试
     */
    // 1.1 加载 http 模块,创建 Web 服务对象
    const http = require('http')
    const server = http.createServer()
    // 1.2 监听 request 请求事件,设置响应头和响应体
    server.on('request', (req, res) => {
      // 设置响应头-内容类型-普通文本以及中文编码格式
      res.setHeader('Content-Type', 'text/plain;charset=utf-8')
      // 设置响应体内容,结束本次请求与响应
      res.end('欢迎使用 Node.js 和 http 模块创建的 Web 服务')
    })
    // 1.3 配置端口号并启动 Web 服务
    server.listen(3000, () => {
      console.log('Web 服务启动成功了')
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    1.1 解决跨域问题

    接口 jsonp 解决跨域

    // server.js
    const http = require('http')
    const url = require('url')
    
    const app = http.createServer((req, res) => {
      let urlObj = url.parse(req.url, true)
      console.log(urlObj.query.callback)
      switch (urlObj.pathname) {
        case '/api/user':
          res.end(`${urlObj.query.callback}(${JSON.stringify({name:'xxx',age:18})})`)
          break
        default:
          res.end('404.')
          break
      }
    })
    
    app.listen(3000, () => {
      console.log('localhost:3000')
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    <!-- index.html -->
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    
    <body>
      <script>
        const oscript = document.createElement('script');
        oscript.src = 'http://localhost:3000/api/user?callback=test';
        document.body.appendChild(oscript);
        function test(obj) {
          console.log(obj)
        }
      </script>
    
    </body>
    
    </html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    CORS 解决跨域

    // server.js
    const http = require('http')
    const url = require('url')
    
    const app = http.createServer((req, res) => {
      let urlObj = url.parse(req.url, true)
      // console.log(urlObj.query.callback)
      res.writeHead(200, {
        'Content-Type': 'application/json; charset=utf-8',
        // CORS 头
        'Access-Control-Allow-Origin': '*'
      })
      switch (urlObj.pathname) {
        case '/api/user':
          res.end(`${JSON.stringify({ name: 'xxx', age: 18 })}`)
          break
        default:
          res.end('404.')
          break
      }
    })
    
    app.listen(3000, () => {
      console.log('localhost:3000')
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    
    DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Documenttitle>
    head>
    
    <body>
      <script>
        fetch('http://localhost:3000/api/user')
        .then(res=>res.json())
        .then(res=>console.log(res))
      script>
    
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    1.2 作为客户端

    Node.js 既可以做服务端开发,又可以做客户端开发。

    get

    
    DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Documenttitle>
    head>
    
    <body>
      <script>
        fetch('http://localhost:3000/api/user')
        .then(res=>res.json())
        .then(res=>console.log(res))
      script>
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    // get.js
    const http = require('http')
    const https =  require('https')
    const url = require('url')
    
    const app = http.createServer((req, res) => {
      let urlObj = url.parse(req.url, true)
      // console.log(urlObj.query.callback)
      res.writeHead(200, {
        'Content-Type': 'application/json; charset=utf-8',
        // CORS 头
        'Access-Control-Allow-Origin': '*'
      })
      switch (urlObj.pathname) {
        case '/api/user':
          // 现在作为客户端 去猫眼api请求数据
          // 注意协议要统一:https还是http
          httpget(res)
          break
        default:
          res.end('404.')
          break
      }
    })
    app.listen(3000, () => {
      console.log('localhost:3000')
    })
    function httpget(response) {
      let data = ''
      https.get(`https://i.maoyan.com/api/mmdb/movie/v3/list/hot.json?ct=%E7%9F%B3%E5%AE%B6%E5%BA%84&ci=76&channelId=4`,res => {
        // data 是一份一份的数据收集,end 是最终收集到的所有数据
        res.on('data', chunk => {
          data += chunk
        })
        res.on('end', () => {
          console.log(data)
          response.end(data)
        })
      })
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    另一种写法:

    // get.js
    const http = require('http')
    const https =  require('https')
    const url = require('url')
    
    const app = http.createServer((req, res) => {
      let urlObj = url.parse(req.url, true)
      // console.log(urlObj.query.callback)
      res.writeHead(200, {
        'Content-Type': 'application/json; charset=utf-8',
        // CORS 头
        'Access-Control-Allow-Origin': '*'
      })
      switch (urlObj.pathname) {
        case '/api/user':
          // 现在作为客户端 去猫眼api请求数据
          // 注意协议要统一:https还是http
          // data 收集好的时候调用内部传入的 cb 函数
          httpget((data)=> {
            res.end(data)
          })
          break
        default:
          res.end('404.')
          break
      }
    })
    app.listen(3000, () => {
      console.log('localhost:3000')
    })
    function httpget(cb) {
      let data = ''
      https.get(`https://i.maoyan.com/api/mmdb/movie/v3/list/hot.json?ct=%E7%9F%B3%E5%AE%B6%E5%BA%84&ci=76&channelId=4`,res => {
        // data 是一份一份的数据收集,end 是最终收集到的所有数据
        res.on('data', chunk => {
          data += chunk
        })
        res.on('end', () => {
          console.log(data)
          cb(data)
        })
      })
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    post

    
    DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Documenttitle>
    head>
    
    <body>
      <script>
        fetch('http://localhost:3000/api/user')
        .then(res=>res.json())
        .then(res=>console.log(res))
      script>
    
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    // post.js
    const http = require('http')
    const https = require('https')
    const url = require('url')
    
    const app = http.createServer((req, res) => {
      let urlObj = url.parse(req.url, true)
      // console.log(urlObj.query.callback)
      res.writeHead(200, {
        'Content-Type': 'application/json; charset=utf-8',
        // CORS 头
        'Access-Control-Allow-Origin': '*'
      })
      switch (urlObj.pathname) {
        case '/api/user':
          // 现在作为客户端 去小米优品 api 请求数据
          // 注意协议要统一:https还是http
          httpPost((data) => {
            res.end(data)
          })
          break
        default:
          res.end('404.')
          break
      }
    })
    app.listen(3000, () => {
      console.log('localhost:3000')
    })
    function httpPost(cb) {
      let data = ''
      const options = {
        hostname: 'm.xiaomiyoupin.com',
        port: '443', // 80 是 http 默认端口号,443 是 https 默认端口号
        path: '/mtop/market/search/placeHolder',
        methods: "POST",
        headers: {
          "Content-Type": "application/json",
        }
      }
      const req = https.request(options, (res) => {
        res.on('data', (chunk) => {
          data += chunk
        })
        res.on('end', () => {
          cb(data)
        })
      })
      req.write(JSON.stringify([{}, { baseParam: { ypClient: 1 } }]))
      req.end()
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51

    1.3 爬虫

  • 相关阅读:
    HTTP详解(HTTP的特点,状态码,工作原理,GET和POST的区别,如何解决无状态通信)!!!
    C++&QT day11
    猿辅导联合多方专家共议新课标:语文将更强调“实践性”
    Java核心知识体系3:异常机制详解
    bat互联网大厂的人都用什么相亲交友平台?盘点互联网人用的脱单软件
    freeswitch 变声模块mod_soundtouch、mod_ladspa
    7-5 改写二分搜索算法
    14:00面试,14:06就出来了,问的问题有点变态。。。。。。
    内存对齐规则
    我们对 .NET 9 的愿景
  • 原文地址:https://blog.csdn.net/XiugongHao/article/details/133687732