jsonp的nodejs实战
我打开了2个web服务,127.0.0.1:3000,127.0.0.1:2999
jsonp首先要求后台提供一个可以返回 fnName(result) 字符串的接口;
然后前端首先定义好fnName(result)的方法,然后使用script的src属性访问此接口。
可以动态和删除script标签,就可以请求跨域的接口了,缺点是要后台提供特定的接口
var http = require("http");var querystring = require('querystring');var url = require('url');var serverHTML = http.createServer((req, res) => {var indexHtml ='<html>\n'+ '<meta charset="utf-8">\n'+ '<head>\n'+ '<title>跨域请求</title>\n'+ '<script>\n'+ 'function abc(result){\n'+ 'var data = JSON.stringify(result);\n'+ 'document.getElementById("text").innerHTML = data;\n'+ '}\n'+ 'window.onload = function () {\n'+ 'document.getElementById("btn").onclick = function () {\n'+ 'var script = document.createElement("script");\n'+ 'script.src = "http://127.0.0.1:3000?callback=abc";\n'+ 'document.getElementsByTagName("head")[0].appendChild(script);\n'+ 'var script2 = document.createElement("script");\n'+ 'script2.src = "//common.cnblogs.com/scripts/jquery-2.2.0.min.js"\n'+ 'document.getElementsByTagName("head")[0].appendChild(script2);\n'+ '}\n'+ '}\n'+ '</script>\n'+ '</head>\n'+ '<body>\n'+ '<input id="btn" type="button" value="跨域获取数据" />\n'+ '<div id="text"></div>\n'+ '</body>\n'+ '</html>\n'res.writeHead(200, { 'Content-Type': 'text/html' });res.write(indexHtml);res.end();}).listen(2999);var server = http.createServer((req, res) => {/*const headers = JSON.stringify(req.headers);const cookie = req.headers.cookie;res.write('headers:' + headers);res.write('\n');res.write('\n');res.write('cookie:' + cookie);res.write('\n');res.write('\n');res.write('method:' + JSON.stringify(req.method));res.write('\n');res.write('\n');res.write('url:' + req.url);*/if (req.method === 'GET') {console.log('GET');var params = url.parse(req.url, true).query;var callback = params.callback + '(' + '"aaa"' + ')';res.write(callback);console.log(params);res.end();} else if (req.method === 'POST') {// 未完待续接收post请求console.log('post');var body = "";req.on('data', function (chunk) {body += chunk; //一定要使用+=,如果body=chunk,因为请求favicon.ico,body会等于{}console.log("chunk:", chunk);});req.on('end', function () {// 解析参数body = querystring.parse(body); //将一个字符串反序列化为一个对象console.log("body:", body);// 设置响应头部信息及编码\<br><br> res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});if (body.name && body.url) { // 输出提交的数据res.write("网站名:" + body.name);res.write("<br>");res.write("网站 URL:" + body.url);} else { // 输出表单res.write();}res.end();});}}).listen(3000);
笔试题四
实现一个jsonp函数,仅需要支持jsonp(url)一种调用方式即可(仅有url一个传参),例如: jsonp(‘//t.alicdn.com/t/gettime?callback=cb’).then(result=>console.dir(result))
未完待续
