JSONP原理及自定义JSONP函数


jsonp(JSON with Padding)是一种使用模式,可以实现跨域获取数据,原理是基于由于script标签不受限于同源策略,script标签可以通过src属性请求到其他服务器上的数据

浏览器同源策略:在当前网页中,若想到发送一个请求,请求url必须满足 协议,域名,端口 三者相同,才能得到正常响应,否则属于跨域请求,浏览器会限制跨域请求。

jsonp是实现跨域一种的方式。

一、服务器端代码实现

let express = require('express'); var http = require('http'); let port = 1013;
let app = new express(); app.get('/say', function (req, res) {   let { cb } = req.query;
  res.write(`${cb}('hello,jsonp')`);   res.end(); }); app.listen(port, () => {   try {     console.log(`http server start listening at http://localhost:${port}`);   } catch (error) {} });

二、客户端代码1


                Document


三、客户端代码2

使用自定义jsonp函数,效果同上





    
    
    
    Document