剖析JSONP原理的小例子

1. 服务器端代码(Node.js

// 导入 http 内置模块const http = require(‘http‘);// 这个核心模块,能够帮我们解析 URL地址,从而拿到 pathname queryconst urlModule = require(‘url‘);// 创建一个 http 服务器const server = http.createServer();// 监听 http 服务器的 request 请求server.on(‘request‘, function (req, res) {
  // 解构赋值,将pathname重命名为url const { pathname: url, query }
= urlModule.parse(req.url, true); if (url === ‘/getScript‘) { let data = { name: ‘tom‘, age: 6, friend: ‘jerry‘ }; // 把需要调用的方法和需要传递的参数放到一个字符串中发给客户端 let str = `${query.callback}(${JSON.stringify(data)})`; // res.end 发送给客户端, 客户端去把这个字符串,当作JS代码去解析执行 res.end(str); } else { res.end(‘404‘) }});// 指定端口号并启动服务器监听server.listen(3000, function () { console.log(‘server is running ...‘);});

2. 客户端代码

<script>function showInfo(data){ console.log(data);}</script><script src="http://127.0.0.1:3000/getScript?callback=showInfo"></script>

3. 备注

3.1 在客户端先定义好方法,然后通过script标签的src属性发起get请求将方法名传递到服务端。在服务端通过模板字符串将获取的方法名和需要返回的数据包装起来然后响应给客户端,这样就完成了JSONP的数据传递。

3.2 es6中的模板字符串:

模板字符串(template string)是增强版的字符串,用反引号(`)标识。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。

// 普通字符串`In JavaScript ‘\n‘ is a line-feed.`// 多行字符串`In JavaScript this is not legal.`console.log(`string text line 1string text line 2`);// 字符串中嵌入变量var name = "tom", friend = "jerry";`Hello ${name}, how are you ${friend}?`

 3.3 解构赋值

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

相关文章