zoukankan      html  css  js  c++  java
  • 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)
    

     请求结果:

     

  • 相关阅读:
    Linux 安装SonarQube
    Linux 安装postgresql
    如何为chrome浏览器设置socks5代理
    echarts tab切换宽度变为100px解决方案
    将url参数转为对象
    一行js代码实现时间戳转时间格式
    解决问题的方法论
    李笑来的幻灯课
    随便写写(最近更新于2021/07/18早)
    谈谈装系统这件事
  • 原文地址:https://www.cnblogs.com/tengrl/p/10724656.html
Copyright © 2011-2022 走看看