首页 > 代码库 > node实现jsonp跨域
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=http://www.mamicode.com/JSON.parse(data);//因为data是buffer要把他变成json
data=http://www.mamicode.com/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\n‘);
}
});
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>
node实现jsonp跨域