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个月,想找一个基础的前端工作

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值