每个.js文件都是一个模块:
对外暴露变量: module.exports = variable;
引用暴露变量: var ref = require('module_name');
前端请求代码:
<!DOCTYPE html>
<head>
<title>jsonp</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<script>
function test(data){
alert(data.name);
};
</script>
<script src="http://127.0.0.1:8080/jsonp?callback=test"></script>
</body>
</html>
启动服务器 , 验证请求url:
//通过require将http库包含到程序中
var http = require('http');
//创建新的HTTP服务器
http.createServer();
//引入url模块解析url字符串
var url = require('url');
//引入querystring模块处理query字符串
var querystring = require('query');
//通过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 = {
"name": "Monkey"
};
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('Hell World\n');
}
});
server.listen('8080');
console.log('Server running!');
JSON.stringify() :
将一个JavaScript值(对象或者数组)转换为一个 JSON字符串
url.parse(req.url) 返回值:
{
protocol: 'http:',
slashes: true, auth: 'user:pass',
host: 'host.com:8080', port: '8080',
hostname: 'host.com', hash: '#hash',
search: '?query=string',
query: 'query=string',
pathname: '/p/a/t/h',
path: '/p/a/t/h?query=string',
href: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'
}
没有设置第二个参数为true时,query属性为一个字符串类型
动态生成script:
//动态创建script标签,并请求
function addScriptTag(src){
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.src = src;
document.body.appendChild(script);
};
//如:在onload后,跨域请求
window.onload = function(){
addScriptTag('http://127.0.0.1:8080/jsonp?callback=monkey');
};
//回调的方法,且必须为全局方法,不然会报错
function monkey(data){
alert(data);
};
参考:https://www.cnblogs.com/giggle/p/5496596.html