node实现jsonp跨域
2021-06-23 10:04
YPE html>
标签:div read lower world string oca object prot click
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\n‘);
}
});
server.listen("3000");
console.log("server running at localhost:3000");
前端代码:
node实现jsonp跨域
标签:div read lower world string oca object prot click
原文地址:http://www.cnblogs.com/ziqian9206/p/7162087.html