携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第6天,点击查看活动详情
http模块补充
jsonp
Jsonp 全称是Json with Padding,是 json 的一种"使用模式",可以让网页从别的域名获取数据,即跨域读取数据。 前端在使用Ajax请求后端接口时,如果域名或端口不一致就会产生跨域问题,但是,在页面上引入不同域上的js脚本或图片却是可以自由访问的。
例如通过CDN引入 jQuery
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
于是就想到了后端不返回Json格式的数据,而是返回一段调用某个函数的js代码,供前端来调用和处理,实现跨域。
新建jsonp.js
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/html;charset=utf-8" });
let urlobj = url.parse(req.url, true);
switch (urlobj.pathname) {
case '/':
case 'home':
res.write(`<html><h1>这是首页</h1></html>`);
break;
case '/api/aa':
res.end(`${urlobj.query.callback}(${JSON.stringify({
name: "jiaji",
age: 20
})})`);
break;
default:
res.end('404 Not Found');
}
}).listen(3000, () => {
console.log('http://localhost:3000');
})
新建index.html
<body>
<!-- 前端请求jsonp接口 -->
<script>
let oscript = document.createElement("script");
//将test函数名传给后端
oscript.src = "http://localhost:3000/api/aa?callback=test";
document.body.appendChild(oscript);
function test(obj){
//后端返回的数据
console.log(obj);
}
</script>
</body>
后端一般给前端返回
json数据,而使用Jsonp的特殊之处就在于前端会传递一个函数名给后端,接着后端返回数据时会将这个函数名来包裹住json数据,最终返给前端的就是一段js代码了,这样就巧妙地解决了跨域的问题。启动服务 node jsonp.js
使用服务器的方式打开index.html,在控制台就能看到后端返回的数据了
cors
CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出XMLHttpRequest请求。
新建cors.js
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "application/json;charset=utf-8",
//后端在响应时,只需要在响应头加上这个属性即可
"access-control-allow-origin": "*"
});
let urlobj = url.parse(req.url, true);
switch (urlobj.pathname) {
case '/':
case 'home':
res.write(`<html><h1>这是首页</h1></html>`);
res.end();
break;
case '/api/aa':
res.end(`${JSON.stringify({
name: "jiaji",
age: 20
})}`);
break;
default:
res.end('404 Not Found');
}
}).listen(3000, () => {
console.log('http://localhost:3000');
})
新建index.html
<body>
<script>
fetch("http://localhost:3000/api/aa")
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log(error));
</script>
</body>
"access-control-allow-origin": "*"表示允许任意地址请求接口,如果希望指定url,把*更改为指定的url即可。启动服务 node cors.js
使用服务器的方式打开index.html,在控制台就能看到后端返回的数据了
模拟get请求
前端在向后端接口请求数据时,后端也可以作为客户端向别的接口请求地址,例如使用get请求猫眼的数据(仅用于学习,如有侵犯,请联系删除)。
新建get.js
const http = require('http');
const https = require('https');
const url = require('url');
const server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "application/json;charset=utf-8",
//解决跨域问题
"access-control-allow-origin": "*"
});
let urlobj = url.parse(req.url, true);
switch (urlobj.pathname) {
case '/api/aa':
//作为客户端 去猫眼请求数据
//传入回调函数,将数据返回出去
httpGet((data) => res.end(data));
break;
default:
res.end('404 Not Found');
}
}).listen(3000, () => {
console.log('http://localhost:3000');
})
function httpGet(callback) {
let data = "";
//发起get请求,注意是https协议
https.get(`https://i.maoyan.com/api/mmdb/movie/v3/list/hot.json?ct=%E6%88%90%E9%83%BD&ci=59&channelId=4`, (res) => {
//监听事件,将响应的数据拼接成字符串
res.on("data", (chunk) => {
data += chunk;
});
//返回数据给前端
res.on("end", () => {
callback(data);
});
})
}
新建index.html
<!-- 代码同cors的index.html -->
前端请求后端接口时,后端作为客户端去请求猫眼的数据,最后返回给前端。
启动服务 node get.js
使用服务器的方式打开index.html,在控制台就能看到后端返回的数据了
模拟post请求
前端请求后端接口,后端作为客户端请求小米有品的数据,返回给前端(仅用于学习,如有侵犯,请联系删除)。
新建post.js
const http = require('http');
const https = require('https');
const url = require('url');
const server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "application/json;charset=utf-8",
"access-control-allow-origin": "*"
});
let urlobj = url.parse(req.url, true);
switch (urlobj.pathname) {
case '/api/aa':
//作为客户端 去小米优品要数据
httpPost((data) => res.end(data));
break;
default:
res.end('404 Not Found');
}
}).listen(3000, () => {
console.log('http://localhost:3000');
})
//options配置
const options = {
protocol: 'https:', //协议
hostname: 'm.xiaomiyoupin.com', //域名
method: 'POST', //请求方式
port: 443, //端口
path: '/mtop/market/search/placeHolder', //请求地址
headers: {
'Content-Type': 'application/json', //参数数据类型
}
}
function httpPost(callback) {
let data = "";
//发起post请求
let req = https.request(options, (res) => {
res.on('data', chunk => data += chunk)
res.on('end', () => {
callback(data)
})
})
//请求的参数
req.write(JSON.stringify([{}, {"baseParam": {"ypClient": 1}}]));
req.end()
}
新建index.html
<!-- 代码同cors的index.html -->
启动服务 node post.js
使用服务器的方式打开index.html,在控制台就能看到后端返回的数据了