JSONP

前端封装方法

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function jsonP(option) {
            var callbackName = 'jsonp_' + Math.random().toString().substr(2) +
                Math.random().toString().substr(2);
            //将用户通过对象命名空间传递进来的函数挂在到全局
            window[callbackName] = function (data) {
                option.success(data);
                //这里才以为这可以删除script标签了
                document.body.removeChild(script);
            }
            //1解决url问题
            //2解决回到处理函数问题
            option.url = option.url + '?callback=' + callbackName;
            var script = document.createElement('script');
            script.src = option.url;
            //将script挂在到body上
            document.body.appendChild(script)

        }
        jsonP({
            url: 'http://localhost:3000/',
            type: '',
            data: '',
            success: function (data) {
                console.log(data)
            }
        })
    </script>
</body>

</html>

 

后端处理

const express=require('express');

const app=express();

app.get('/',(req,res,next)=>{
    console.log(`收到客户端请求了:${req.url}`)
    var data=JSON.stringify({
        foo:'bar',
        list:[1,2,3,4]
    })
    res.end(`${req.query.callback}(${data})`)
})

app.listen(3000,()=>{
    console.log('server start and listen at 3000')
})

 

 
posted @ 2021-06-27 19:08  还有什么值得拥有  阅读(28)  评论(0编辑  收藏  举报