Node.js HTTP API 是非常低层的。是开启搭建服务的基础模块,本次搭建使用log4js来记录打印信息
get
默认的get请求,简单实现方式
const http = require('http')
const https = require('https')
const logger = require('../../utils/log')
const queryString = require('querystring')
const server = http.createServer((request, response) => {
// logger.debug(res)
// logger.debug(res)
// const url = request.url
// logger.debug(url)
// response.writeHead(200, {
// 'content-type': 'application/json;charset-utf-8'
// })
// response.write(`{'url':${url}}`)
// response.end('{"x":200}')
// let data = ''
// request.on('data', (chunk) => {
// data += chunk
// })
// request.on('end', () => {
// response.writeHead(200, {
// 'content-type': 'application/json;charset-utf-8'
// })
// logger.debug(JSON.stringify(queryString.parse(data)))
// response.end()
// })
https.get('https://www.xiaomiyoupin.com/mtop/market/cat/list', (result) => {
let data = ''
result.on('data', (chunk) => {
data += chunk
})
result.on('end', () => {
response.writeHead(200, {
'content-type': 'application/json;charset-utf-8'
})
response.write(data)
response.end()
})
})
// https.get('https://www.xiaomiyoupin.com/mtop/market/cat/list', (result) => {
// let data = ''
// result.on('data', (chunk) => {
// data += chunk
// })
// result.on('end', () => {
// response.writeHead(200, {
// 'content-type': 'application/json;charset-utf-8'
// })
// logger.debug(data)
// response.end()
// })
// })
})
server.listen(2139, () => {
console.log('localhost:2139')
})
post
此处列举了一个简单的定时发送post请求例子()
const http = require('http')
const querystring = require('querystring')
const postData = querystring.stringify({
province: '上海',
city: '上海',
district: '宝山区',
})
const options = {
protocol: 'http:',
hostname: 'localhost',
method: 'post',
port: 3000,
path: '/data',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
}
const server = http.createServer((req, res) => {
const request = http.request(options, (result) => {
})
request.write(postData)
request.end()
res.end()
})
// function doPost() {
// let data
// let req = https.request(options, (res) => {
// res.on('data', chunk => data += chunk)
// res.on('end', () => {
// console.log(data)
// })
// })
// req.write(postData)
// req.end()
// }
// setInterval(() => {
// doPost()
// }, 1000)
server.listen('2139', () => {
console.log('localhost:2139')
})
jsonp
由于浏览器有同源策略限制,采用解决跨域方案jsonp,JavaScript请求没有限制,利用请求回来的代码,直接执行,实现跨域请求
server.js
const http = require('http')
const server = http.createServer((req, res) => {
let url = req.url
switch (url) {
case '/api/data':
res.write('alert(0111)')
break;
default:
res.write('page not found')
}
res.end()
})
server.listen('2139', () => {
console.log('localhost:2139')
})
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>jsonp</title>
</head>
<body>
<script>
function getData(data) {
console.log(data);
}
</script>
<script scr="http://localhost:2139/api/data"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
</body>
</html>
cors
在response的header里面返回’Access-Control-Allow-Origin’: ‘*’,设置为响应所以请求,解决跨域
const server = http.createServer((req, res) => {
let url = req.url
res.writeHead(200, {
'content-type': 'application/json;charset=utf-8',
'Access-Control-Allow-Origin': '*'
})
res.write(url)
res.end()
})
proxy
利用中间件proxy,代理请求
const http = require('http')
const { createProxyMiddleware } = require('http-proxy-middleware')
// console.log(createProxyMiddleware)
const server = http.createServer((req, res) => {
let url = req.url
if (/\/ajax/.test(url)) {
const proxy = createProxyMiddleware('/ajax', {
target: 'https://lady.vip.com',
changeOrigin: true
})
// 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
proxy(req, res)
} else if (/\/api/.test(url)) {
const proxy2 = createProxyMiddleware('/api', {
target: 'https://m.lagou.com',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
})
proxy2(req, res)
}
// res.end()
})
server.listen(2139, () => {
console.log('2139succ')
})