【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 爬虫

相关推荐
Misnice2 小时前
Webpack、Vite、Rsbuild区别
前端·webpack·node.js
毕设源码-朱学姐1 天前
【开题答辩全过程】以 基于Node.js的书籍分享平台设计与实现为例,包含答辩的问题和答案
node.js
前端 贾公子1 天前
Node.js 如何处理 ES6 模块
前端·node.js·es6
周杰伦的稻香1 天前
Hexo搭建教程
java·node.js
毕设源码-钟学长1 天前
【开题答辩全过程】以 基于node.js vue的点餐系统的设计与实现为例,包含答辩的问题和答案
前端·vue.js·node.js
朝朝暮暮an2 天前
Day 2|Node.js 运行机制、模块系统与异步初探
node.js
aidou13142 天前
Visual Studio Code(VS Code)安装步骤
vscode·npm·node.js·环境变量
止观止2 天前
告别 require!TypeScript 5.9 与 Node.js 20+ 的 ESM 互操作指南
javascript·typescript·node.js
一只专注api接口开发的技术猿2 天前
淘宝商品详情API的流量控制与熔断机制:保障系统稳定性的后端设计
大数据·数据结构·数据库·架构·node.js
天远数科2 天前
天远车辆过户查询API集成指南:Node.js 全栈视角下的二手车数据挖掘
大数据·数据挖掘·node.js·vim