zhangzheng-zz / blog

1 stars 0 forks source link

前端跨域 #12

Open zhangzheng-zz opened 3 years ago

zhangzheng-zz commented 3 years ago

jsonp

// index.html
<!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>
      // 动态创建 script 脚本
      function createScript(src) {
        let script = document.createElement("script");
        script.setAttribute("type", "text/javascript");
        script.src = src;
        document.body.appendChild(script);
      }
      // 发送 jsonp 请求 callback 后面是指定回调方法名
      window.onload = function () {
        createScript('http://localhost:3000/jsonp?callback=getData')
      };
      // 定义要执行的回调方法并获取数据
      function getData (data) {
        alert(`回调执行`)
        console.log(`执行回调,参数:`,data)
      }
    </script>
  </body>
</html>
// serve.js
var http = require('http');
var url = require('url');
var querystring = require('querystring');

//创建新的HTTP服务器
var server = http.createServer();
//通过request事件来响应request请求
server.on('request',function(req, res){
    var urlPath = url.parse(req.url).pathname;
    var qs = querystring.parse(req.url.split('?')[1]);
    if(urlPath === '/jsonp' && qs.callback){
        res.writeHead(200,{'Content-Type':'application/json;charset=utf-8'});
        var data = {
            "value": "I am a data from jsonp!"
        };
        data = JSON.stringify(data);
        var callback = qs.callback+'('+data+');';
        res.end(callback);
    }
    else{
        res.writeHead(200, {'Content-Type':'text/html;charset=utf-8'});
        res.end('hello');
    }
});

//监听3000端口
server.listen('3000');
console.log('Server running!');