1. event (发布订阅模式)
import EventEmitter from 'events'
const event = new EventEmitter()
event.on("play",()=> {
console.log("触发play");
})
event.on("name",()=> {
console.log("触发name");
})
setTimeout(() => {
event.emit("play")
},1000)
2.jsonp
html部分
// jsonp接口调用
var jsonScript = document.createElement("script")
jsonScript.src = "http://localhost:3000/list1?callBack=myFun"
document.body.appendChild(jsonScript)
function myFun(obj) {
console.log(obj);
}
js部分
import http from 'http'
import url from 'url'
http.createServer((req, res) => {
var urlobj = url.parse(req.url, true)
switch (urlobj.pathname) {
case "/list":
// jsonp
res.end(`${urlobj.query.callBack}(${ JSON.stringify({
name: 'world',
age: 20
})})`)
break;
default:
res.end("404")
}
}).listen(3000, () => {
console.log('Start')
})
3.GET请求
前端部分
fetch("http://localhost:3000/list")
.then(res => res.json())
.then(res => {
console.log(res);
})
js部分
import http from 'http'
import https from 'https'
import EventEmitter from 'events'
import url from 'url'
var event=null
http.createServer((req, res) => {
var myUrl = url.parse(req.url, true)
res.writeHead(200, {
"Content-Type": "application/json;charset=utf-8",
"access-control-allow-origin":"*"
})
switch (myUrl.pathname) {
case "/list":
// 客户端抓取数据
// 第一种方法 (耦合度比较高)
// httpget(res)
// 第二种方法 回调函数(耦合度低)
// httpget((data) => {
// res.end(data)
// })
// 第三种方法event发布订阅 (推荐)
event = new EventEmitter()
event.on("play", (data) => {
res.end(data)
})
httpget()
break;
default:
res.end("404")
}
}).listen(3000, () => {
console.log("服务已开启");
})
function httpget(response) {
// 定义数据
var data = ""
https.get(`https://i.maoyan.com/api/mmdb/movie/v3/list/hot.json?ct=%E9%9D%92%E5%B2%9B&ci=60&channelId=4`, (res) => {
// 收集数据
res.on("data", (chunk) => {
data += chunk
})
// 全部数据收集完毕
res.on("end", () => {
console.log(data);
// 第一种方法 (耦合度比较高)
// response.end(data)
// 第二种方法 回调函数(耦合度低)
// response(data)
// 第三种方法 event (推荐)
event.emit("play",data)
})
})
}
4.POST请求
前端部分
fetch("http://localhost:3000/list")
.then(res => res.json())
.then(res => {
console.log(res);
})
js部分
import http from 'http'
import https from 'https'
import url from 'url'
http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "application/json;charset=utf-8",
"access-control-allow-origin":"*"
})
var myURL = url.parse(req.url, true)
switch (myURL.pathname) {
case "/list":
httppost((data) => {
res.end(data)
})
break;
default:
res.end("404")
}
}).listen(3000, () => {
console.log("开启服务");
})
function httppost(cb){
var data = ""
// 必须的参数
var options = {
hostname: "m.xiaomiyoupin.com",
port: "443",
path: "/mtop/market/search/placeHolder",
method: "POST",
headers: {
"Content-Type":"application/json"
}
// 还有一种标准
// "Content-Type":"x-www-form-urlencoded"
}
var req=https.request(options, (res) => {
res.on("data", (chunk) => {
data+=chunk
})
res.on("end", () => {
cb(data)
})
})
// 发起请求
// req.write("name=wanye&age=20")
req.write(JSON.stringify([{}, { "baseParam": { "ypClient": 1 } }]))
req.end()
}