jsonp 实现前端跨域

1、基于ajax 发起jsonp 请求。

前端代码:

 let url = 'http://localhost:8001/';
        $.ajax({
            type: 'get',
            dataType: 'jsonp',
            url: url,
            jsonp: "callback",
            success: function (res) {
                console.log('success',res)
            },
            error (err) {
                console.error(err)
            }
        })

 后端代码:(node server)

let http = require('http');
http.createServer((req,res) => {
    res.setHeader('Content-Type', 'application/json')
    res.end(JSON.stringify({
        data: 'hello word!',
        status: 'success'
        }))
}).listen(8001)

 请求结果:

2、callback函数回调,动态创建script标签

前端代码:

             let url = 'http://localhost:8001/';   
       function ajaxHandle (data) {
            console.log('接受data', data)
        }
       
        var script = document.createElement('script');
        script.setAttribute('src', url);
        document.getElementsByTagName('head')[0].appendChild(script)

后端代码:(node server)

let http = require('http');
http.createServer((req,res) => {
    res.setHeader('Content-Type', 'application/json')
    let callback = req.url.split('&')[0].split('=')[1]; //  获取callback 函数
    let data = callback + '(' + JSON.stringify({data: 'hello word!'}) + ')'; // 拼接数据
    res.end(data)
}).listen(8001)

 请求结果:

 

猜你喜欢

转载自www.cnblogs.com/tengrl/p/10724656.html
今日推荐