JSONJavaScript技术

JSONP

2022-03-24  本文已影响0人  申_9a33

同源策略


跨域


JSONP


1.跨域的简单原理

<!DOCTYPE html>
<html >
<head>
    <title>Document</title>
</head>
<body>
</body>
<script src="http://localhost:8081/test.js"></script>
</html>
alert("success");

2.JSONP的实现模式--CallBack

<!DOCTYPE html>
<html >
<head>
    <title>Document</title>
</head>
<body>
</body>
<script type="text/javascript">
    //定义一个回调函数
    function callback(data) {
        alert(data.message);
    }
</script>
<script src="http://localhost:8081/test.js"></script>
</html>
callback({message:"success"});

3.node服务端实现一个用于JSONP调用的接口

const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();

// 主页
let routerHome = new Router();
routerHome.get('/', async (ctx) => {
    ctx.body = 'Hello World';
})

// JSONP
let routerJsonp = new Router();
routerJsonp.get('/data1', async (ctx) => {
    let cb = ctx.request.query.callback;
    ctx.type = 'text';
    ctx.body = cb + '(' + JSON.stringify({
        message:`${ctx.request.query.name} JSONP`
    }) + ')';
})

// 汇总
let router = new Router();
router.use('/',routerHome.routes(),routerHome.allowedMethods())
router.use('/jsonp', routerJsonp.routes(), routerJsonp.allowedMethods());
app.use(router.routes()).use(router.allowedMethods())


app.listen(8081);

修改http://localhost:8080/

<script src="http://localhost:8081/jsonp/data1?name=小张&callback=callback"></script>
   function callback(data) {
       alert(data.message);
   }
   //添加<script>标签的方法
   function addScriptTag(src){
   var script = document.createElement('script');
       script.setAttribute("type","text/javascript");
       script.src = src;
       document.body.appendChild(script);
   }
   
   window.onload = function(){
       addScriptTag("http://localhost:8081/jsonp/data1?name=小张&callback=callback");
   }

总结

JSONP 是通过script的src属性,不受同源策略限制,然后在服务端解析query的参数,返回客户端客户需要的text格式的内容;客户端预先定好callback函数;而返回的text中则会调用callback,并且传入服务端的数据。从而实现客户端跨域请求

上一篇 下一篇

猜你喜欢

热点阅读