node实现jsonp跨域

1. 搭建node server

//引入模块

var http=require("http");

var fs=require("fs");
var url = require('url');
var querystring = require('querystring');

//创建服务器
var server=http.createServer();
server.on("request",function(req,res){
    console.log(req.url.split('?')[1])
    var urlpath=url.parse(req.url).pathname;
    var qs = querystring.parse(req.url.split('?')[1]);//callback=result
    if(urlpath === '/jsonp'){
                res.writeHead(200,{'Content-Type':'application/json;charset=utf-8'});
                function isJson(obj){
                    return typeof(obj)=="object"&&Object.prototype.toString.call(obj).toLowerCase()=="[object ]"
                }
                 fs.readFile("fs.json",function(err,data){
                     if(err){console.log(err)}
                     data=JSON.parse(data);//因为data是buffer要把他变成json
                     data=JSON.stringify(data)
                     var callback = qs.callback+'('+data+');';//callback:test({json})
                    res.end(callback);//res.end参数为buffer或者string
                 })
            }else{
                res.writeHead(200, {'Content-Type':'text/html;charset=utf-8'});
                res.end('Hell World ');
            }
});
server.listen("3000");
console.log("server running at localhost:3000");

前端代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jsonp</title>
</head>
<body>
    <div id="box">hahahaha</div>
    <button id="but">click it</button>
    
    <script>
        function test(data){
                            alert(data.name);
                        }
    </script>
    <script src="http://localhost:3000/jsonp?callback=test"></script>

</body>
</html>

原文地址:https://www.cnblogs.com/ziqian9206/p/7162087.html