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

相关推荐
谢尔登1 小时前
【Node.js】semver 语义化版本控制
node.js
空白诗2 小时前
使用 nvm 管理 node 版本:如何在 macOS 和 Windows 上安装使用nvm
windows·macos·node.js·nvm
low神4 小时前
前端进阶,使用Node.js做中间层,实现接口转发和服务器渲染
服务器·前端·javascript·中间件·node.js·前端面试题
赵啸林17 小时前
npm发布插件超级简单版
前端·npm·node.js
翔云API21 小时前
人证合一接口:智能化身份认证的最佳选择
大数据·开发语言·node.js·ocr·php
谢尔登1 天前
Babel
前端·react.js·node.js
lxcw1 天前
npm ERR! code CERT_HAS_EXPIRED npm ERR! errno CERT_HAS_EXPIRED
前端·npm·node.js
布丁椰奶冻1 天前
解决使用nvm管理node版本时提示npm下载失败的问题
前端·npm·node.js
影子落人间1 天前
已解决npm ERR! request to https://registry.npm.taobao.org/@vant%2farea-data failed
前端·npm·node.js
又写了一天BUG1 天前
npm install安装缓慢及npm更换源
前端·npm·node.js