Node.js HTTP API 是非常低层的。是开启搭建服务的基础模块,本次搭建使用log4js来记录打印信息

get

默认的get请求,简单实现方式

  1. const http = require('http')
  2. const https = require('https')
  3. const logger = require('../../utils/log')
  4. const queryString = require('querystring')
  5. const server = http.createServer((request, response) => {
  6. // logger.debug(res)
  7. // logger.debug(res)
  8. // const url = request.url
  9. // logger.debug(url)
  10. // response.writeHead(200, {
  11. // 'content-type': 'application/json;charset-utf-8'
  12. // })
  13. // response.write(`{'url':${url}}`)
  14. // response.end('{"x":200}')
  15. // let data = ''
  16. // request.on('data', (chunk) => {
  17. // data += chunk
  18. // })
  19. // request.on('end', () => {
  20. // response.writeHead(200, {
  21. // 'content-type': 'application/json;charset-utf-8'
  22. // })
  23. // logger.debug(JSON.stringify(queryString.parse(data)))
  24. // response.end()
  25. // })
  26. https.get('https://www.xiaomiyoupin.com/mtop/market/cat/list', (result) => {
  27. let data = ''
  28. result.on('data', (chunk) => {
  29. data += chunk
  30. })
  31. result.on('end', () => {
  32. response.writeHead(200, {
  33. 'content-type': 'application/json;charset-utf-8'
  34. })
  35. response.write(data)
  36. response.end()
  37. })
  38. })
  39. // https.get('https://www.xiaomiyoupin.com/mtop/market/cat/list', (result) => {
  40. // let data = ''
  41. // result.on('data', (chunk) => {
  42. // data += chunk
  43. // })
  44. // result.on('end', () => {
  45. // response.writeHead(200, {
  46. // 'content-type': 'application/json;charset-utf-8'
  47. // })
  48. // logger.debug(data)
  49. // response.end()
  50. // })
  51. // })
  52. })
  53. server.listen(2139, () => {
  54. console.log('localhost:2139')
  55. })

post

此处列举了一个简单的定时发送post请求例子()

  1. const http = require('http')
  2. const querystring = require('querystring')
  3. const postData = querystring.stringify({
  4. province: '上海',
  5. city: '上海',
  6. district: '宝山区',
  7. })
  8. const options = {
  9. protocol: 'http:',
  10. hostname: 'localhost',
  11. method: 'post',
  12. port: 3000,
  13. path: '/data',
  14. headers: {
  15. 'Content-Type': 'application/x-www-form-urlencoded',
  16. 'Content-Length': Buffer.byteLength(postData)
  17. }
  18. }
  19. const server = http.createServer((req, res) => {
  20. const request = http.request(options, (result) => {
  21. })
  22. request.write(postData)
  23. request.end()
  24. res.end()
  25. })
  26. // function doPost() {
  27. // let data
  28. // let req = https.request(options, (res) => {
  29. // res.on('data', chunk => data += chunk)
  30. // res.on('end', () => {
  31. // console.log(data)
  32. // })
  33. // })
  34. // req.write(postData)
  35. // req.end()
  36. // }
  37. // setInterval(() => {
  38. // doPost()
  39. // }, 1000)
  40. server.listen('2139', () => {
  41. console.log('localhost:2139')
  42. })

jsonp

由于浏览器有同源策略限制,采用解决跨域方案jsonp,JavaScript请求没有限制,利用请求回来的代码,直接执行,实现跨域请求
server.js

  1. const http = require('http')
  2. const server = http.createServer((req, res) => {
  3. let url = req.url
  4. switch (url) {
  5. case '/api/data':
  6. res.write('alert(0111)')
  7. break;
  8. default:
  9. res.write('page not found')
  10. }
  11. res.end()
  12. })
  13. server.listen('2139', () => {
  14. console.log('localhost:2139')
  15. })

index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>jsonp</title>
  8. </head>
  9. <body>
  10. <script>
  11. function getData(data) {
  12. console.log(data);
  13. }
  14. </script>
  15. <script scr="http://localhost:2139/api/data"></script>
  16. <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
  17. </body>
  18. </html>

cors

在response的header里面返回’Access-Control-Allow-Origin’: ‘*’,设置为响应所以请求,解决跨域

  1. const server = http.createServer((req, res) => {
  2. let url = req.url
  3. res.writeHead(200, {
  4. 'content-type': 'application/json;charset=utf-8',
  5. 'Access-Control-Allow-Origin': '*'
  6. })
  7. res.write(url)
  8. res.end()
  9. })

proxy
利用中间件proxy,代理请求

  1. const http = require('http')
  2. const { createProxyMiddleware } = require('http-proxy-middleware')
  3. // console.log(createProxyMiddleware)
  4. const server = http.createServer((req, res) => {
  5. let url = req.url
  6. if (/\/ajax/.test(url)) {
  7. const proxy = createProxyMiddleware('/ajax', {
  8. target: 'https://lady.vip.com',
  9. changeOrigin: true
  10. })
  11. // https://lady.vip.com/ajax/getBrandRank.php?part=selling&warehouse=VIP_BJ&areaCode=101101&pagecode=a&brandInfoExt%5Bfields%5D=activeIndexTips,displayEndtime,salesNo,brandImage,mobileImageOne,agio,salesName,brandStoreSn,vendorSaleMessage,isSpecialBanner,hiddenEndTime,iconInfo,link&brandInfoExt%5BstartIndex%5D=0&brandInfoExt%5Bnum%5D=36&preview=0&sell_time_from&time_from&_=1606891993105
  12. proxy(req, res)
  13. } else if (/\/api/.test(url)) {
  14. const proxy2 = createProxyMiddleware('/api', {
  15. target: 'https://m.lagou.com',
  16. changeOrigin: true,
  17. pathRewrite: {
  18. '^/api': ''
  19. }
  20. })
  21. proxy2(req, res)
  22. }
  23. // res.end()
  24. })
  25. server.listen(2139, () => {
  26. console.log('2139succ')
  27. })