1、基于ajax 发起jsonp 请求。

前端代码:

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
 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)

 请求结果:jsonp 实现前端跨域 随笔 第1张

 

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)

 请求结果:

 jsonp 实现前端跨域 随笔 第2张

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄