闲来无事,写写教程~
今天主要是本地模拟一下,客户端发送JSONP请求。
基本原理就是 利用script标签解决跨域。
分别模拟 客户端 和 服务器,还是先看效果:
客户端:运行在本地 8001 端口下
服务器:运行在本地 5002 端口下
上代码
客户端:
本地启动项目:
- 在 terminal 通过
npm i -g http-server -S
安装http服务的包 - 安装好后,在 terminal 当前目录下 ,通过命令
http-server . -p 8001
启动当前项目。
<!--
* @Author: ljl
* @Date: 2022-08-18 11:12:19
* @FilePath: /Test-JSONP/index.html
* @Description: 模拟 客户端(该项目可以通过 `http-server . -p 8001` 启动,8001是客户端的端口)
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>客户端</title>
</head>
<body>
<script>
// 1. 本地定义回调函数
function showInfo123(data) {
console.log('hello, html');
console.log(data);
}
</script>
<!-- 2. 模拟JSONP请求,实际就是利用script标签解决跨域 -->
<script src="http://127.0.0.1:5002/getscript?callback=showInfo123"></script>
</body>
</html>
打开控制台 cmd + option + i
(mac) ctrl + shift + i
(windows) ,就可以看到以下效果,因为服务器还没有启动。
下面搭建服务器
服务器:
在 terminal 通过 node server.js
来启动当前node服务
/*
* @Author: ljl
* @Date: 2022-08-18 11:12:00
* @FilePath: /Test-JSONP/server.js
* @Description: 模拟 服务器(通过 `node server.js` 启动 node 服务监听)
*/
// 导入 http 内置模块,创建一个 http 服务器
const http = require('http');
const server = http.createServer();
// url 核心模块,用于解析 URL 地址
const urlModule = require('url');
// 监听 http 服务器的 request 请求
server.on('request', function (req, res) {
// pathname - 路径;query - ?后拼接的键值对,xxx - 键,query.xxx - 值
const { pathname, query } = urlModule.parse(req.url, true);
// 判断客户端请求的接口
if (pathname === '/getscript') {
// 制作一些返回给客户端的数据
const data = {
name: 'ljl',
age: 18,
gender: 'girl',
};
// 拼接调用回调(客户端会把 scriptStr 当作JS代码去解析执行)
const scriptStr = `${query.callback}(${JSON.stringify(data)})`;
// 将结果发送给客户端
res.end(scriptStr);
} else {
// 当请求接口不对时
res.end('url is not /getscript');
}
});
// 指定服务器的端口号
server.listen(5002, function () {
console.log('server listen at http://127.0.0.1:5002');
});
启动服务后,terminal 为下图,开始监听 5002 端口
访问该地址后:正常打印我们的提示信息
这时的客户端,刷新后可以看到,我们已经拿到了服务器的数据
在服务器地址上,拼接:/getscript?callback=1&haha=2
也可以看到我们服务制造的数据
这时,可以在 服务器 代码 server.on
中,加上下面三句 打印看一下:
console.log('[urlModule.parse(req.url, true)]',urlModule.parse(req.url, true));
console.log('[pathname]',pathname);
console.log('[query]', query.callback, query.haha);
terminal打印:可以看到详细信息
[urlModule.parse(req.url, true)] Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: '?callback=1&haha=2',
query: [Object: null prototype] { callback: '1', haha: '2' },
pathname: '/getscript',
path: '/getscript?callback=1&haha=2',
href: '/getscript?callback=1&haha=2'
}
[pathname] /getscript
[query] 1 2