温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JSONP跨域请求的示例分析

发布时间:2020-12-07 13:49:25 来源:亿速云 阅读:106 作者:小新 栏目:web开发

这篇文章主要介绍了JSONP跨域请求的示例分析,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获。下面让小编带着大家一起了解一下。

维基百科的解释:

JSONP (JSON with Padding or JSON-P[1]) is a javascript pattern to request data by loading a <script> tag. It was proposed by Bob Ippolito in 2005.[2] JSONP enables sharing of data bypassing same-origin policy. The policy disallows running JavaScript to read media DOM elements or XHR data fetched from outside the page's origin. The aggregation of the site's scheme, port number and host name identifies as its origin.

我的理解是:

1、前端编写自己的函数,用script标签发送get请求把函数名字带上
2、服务器端接送到请求后获取前端发送请求时的query,添加上自己的数据返回后。
3.、前端获取返回的内容其实就自己的函数调用实参是数据对象。

  • 解释的有点懵逼没关系,用栗子说话。

前端代码

<!doctype html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>
<script>
    //编写调用函数
    function getremotedata(data) {
        console.log(data);
    }
</script>
<!--用script标签get方法把数据请求发送到后端-->
<script src="http://localhost:3999/?callback=getremotedata"></script>
</body>
</html>

后端代码

//用node编写一个简单的服务器
const http = require('http');
const urlModule = require('url');
const server = http.createServer();
server.on('request', function (req, res) {
    //urlModule.parse(req.url.url)的请求 就是这个对象
    // {
    //   protocol: null,
    //   slashes: null,
    //   auth: null,
    //   host: null,
    //   port: null,
    //   hostname: null,
    //   hash: null,
    //   search: '?callback=getremotedata',
    //   query: 'callback=getremotedata',
    //   pathname: '/',
    //   path: '/?callback=getremotedata',
    //   href: '/?callback=getremotedata' }
    // 对象结构赋值得到query是一个对象
    const {pathname: url, query} = urlModule.parse(req.url, true)
    if (url === '/') {
        var data = {
            name: '大毛',
            age: 18,
            gender: '未知'
        };
        // 解析query的请求得到前端发送的函数名称,加上括号调用此函数,函数里加实参servedata返回
        var scripteStr = `${query.callback}(${JSON.stringify(data)})`
        console.log(scripteStr)
        res.end(scripteStr)
    } else {
        res.end('404')
    }
});
server.listen('3999', function () {
    console.log('server is running 3999')
})

这样前端发送请求,无论回调是什么,后端都会返回回调加data数据,就实现了跨域请求啦。

感谢你能够认真阅读完这篇文章,希望小编分享JSONP跨域请求的示例分析内容对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,遇到问题就找亿速云,详细的解决方法等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI