let http = require('http')
let https = require('https')
let url = require('url') // 用于解析url地址
const app = http.createServer((req, res) => {
let urlobj = url.parse(req.url, true) // 转换为对象
console.log(urlobj);
res.writeHead(200, {
"Content-Type": "application/json;charset=utf-8",
"access-control-allow-origin": "*" // 允许所有域通过控制
})
switch (urlobj.pathname) {
case '/api/user':
httpsPOST((data) => res.end(data))
break
default:
res.end('404')
break
}
})
app.listen(8080, () => {
console.log('localhost:8080')
})
function httpsPOST(response) {
// https://m.xiaomiyoupin.com/mtop/mf/resource/data/batchList
let list = ''
const options = {
hostname: 'm.xiaomiyoupin.com', // 域名
port: '443', //端口号
path: '/mtop/mf/resource/data/batchList', // 路径
method: 'POST', // 请求方式
headers: {
"content-type": "application/json; charset=utf-8" // json格式
}
}
let req = https.request(options, (res) => { // request发送post请求
res.on('data', chunk => {
list += chunk
})
res.on('end', () => {
response(list)
})
})
// https.get('https://i.maoyan.com/api/mmdb/movie/v3/list/hot.json?ct=%E5%98%89%E5%85%B4&ci=185&channelId=4',(res)=>{
// res.on("data",(data)=>{
// list+=data
// }) // 有数据返回就会触发,数据流的方式一点一点的返回
// res.on('end',()=>{ // 数据合并到一起后,end可以拿到完整数据
// response(list)
// })
// })
req.write(JSON.stringify([{}, ["newer_popup_ad", "download_options"]])) // 发送字符串
req.end()
}
前端:
<script>
fetch('http://127.0.0.1:8080/api/user').then(res => res.json()).then(res => {
console.log(res);
})
</script>
请登录后查看回复内容