美文网首页
JSONP跨域

JSONP跨域

作者: 云谷小宝 | 来源:发表于2018-12-04 14:56 被阅读0次

    JSONP

    全称:JSON with Padding,可用于解决主流浏览器的跨域数据访问的问题。

    • 通过script标签加载数据的方式去获取数据当做JS代码来执行。
    • 因为加载的数据是JSON格式,所以需要提前在页面上声明一个全局的函数,函数名通过接口传递参数的方式传给后台,后台解析到函数名后再原始数据上包裹这个函数的函数名,发送给前端(JSONP需要对应接口的后端的赔后才能实现)

    代码如下:

    HTML:

    <!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>
        <script src="index1.js"></script>
    </head>
    <body>
    </body>
    </html>
    

    JS部分:

    文件名jsonp1.js

    function loadScript(url) {
       var script = document.createElement('script')
       script.src = url
       script.type = 'text/javascript'
       var head = document.querySelector('head')
       head.appendChild(script)
    }
    function jsonpCallback(data) {
       console.log(JSON.stringify(data))
    }
    

    后端逻辑,文件名为jsonp2.js

    var url = require('url')
    var http = require('http')
    http.createServer(function (req, res) {
        var data = {
            name: "xiaoming"
        };
        var callbackName = url.parse(req.url, true).query.callback
        res.writeHead(200)
        res.end(`${callbackName}(${JSON.stringify(data)})`)
    }).listen(3000, 'localhost')
    console.log('请打开localhost:3000查看结果')
    

    验证结果:


    终端输入node jsonp2.js 打开localhost:3000

    相关文章

      网友评论

          本文标题:JSONP跨域

          本文链接:https://www.haomeiwen.com/subject/aximcqtx.html