【Node.js】http 模块

1. http 模块

js 复制代码
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.1 解决跨域问题

接口 jsonp 解决跨域

js 复制代码
// 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')
})
js 复制代码
<!-- 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>

CORS 解决跨域

js 复制代码
// 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')
})
html 复制代码
<!-- 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>
    fetch('http://localhost:3000/api/user')
    .then(res=>res.json())
    .then(res=>console.log(res))
  </script>

</body>

</html>

1.2 作为客户端

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

get

html 复制代码
<!-- 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>
    fetch('http://localhost:3000/api/user')
    .then(res=>res.json())
    .then(res=>console.log(res))
  </script>
</body>

</html>
js 复制代码
// 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)
    })
  })
}

另一种写法:

js 复制代码
// 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)
    })
  })
}

post

html 复制代码
<!-- 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>
    fetch('http://localhost:3000/api/user')
    .then(res=>res.json())
    .then(res=>console.log(res))
  </script>

</body>

</html>
js 复制代码
// 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.3 爬虫

相关推荐
用户2160763408312 小时前
一个 2 MB 的 .zst 文件,解压出来只有十几 KB
node.js
木头左2 天前
【浏览器自动化】用 CDP 接管本机 Chrome:从一个宿主迁到另一个宿主的设计与踩坑
node.js·浏览器自动化·cdp·技能化·踩坑实践
cpolar技术支持2 天前
把 agent-autoloop 装在 Mac 上:用本机 Node 实跑一次「接活—提问—拍板—接着干」,再用 cpolar 把它的状态页开给不在工位的自己
node.js·内网穿透·cpolar·ai agent·agent-autoloop
SEO_juper3 天前
Node.js 全站 SEO 体检报告生成器:一次查完标题、描述、canonical、H1、图片
开发语言·前端·node.js·html·bash
木头左4 天前
【Node.js】Markdown 转带图片 Word 文档实战:docx 库转换器设计与 5 个踩坑
node.js·word·markdown·文档自动化
思特奇时空智能4 天前
大规模点要素地图渲染性能优化实践
vue.js·arcgis·性能优化·node.js·html·gis·webgl
w3296362716 天前
飞书接单到月度结算:我用一个 DSH 插件跑通鞋类采购 WMS,附 22 项验收
pdf·node.js·飞书·后端开发·ai agent
濮水大叔6 天前
Cabloy/Vona 为什么不需要 NestJS 的 Dynamic Module
typescript·node.js·nestjs
匠云创新6 天前
读完一万段要两分钟:我们把标书读取从 WPS 对象模型搬到了 docx 解析
性能优化·node.js
某哈压力大7 天前
SSH 突然 Connection reset?不是密钥坏了,是 OpenSSL 把 sshd 干趴了
前端·node.js·命令行