JSONP跨域请求的理解(代码示例)

不言
不言 转载
2018-11-26 14:36:36 2175浏览

本篇文章给大家带来的内容是关于JSONP跨域请求的理解(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

对于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数据,就实现了跨域请求啦。

第一写感觉有点语言不清,大家把代码自己敲一遍就懂了

自学前端3个月,想找一个基础的前端工作

以上就是JSONP跨域请求的理解(代码示例)的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:segmentfault,如有侵犯,请联系admin@php.cn删除