我很长一段时间都是PHP(CodeIgniter和WordPress)开发人员,最近才想学习其他一些语言.我已经开始学习Ruby(在Rails和Sinatra上),Python(带有Flask框架)和带有node.js的Javascript.
我决定使用这些语言创建我能想到的最基本的应用程序,URL扩展器.我已经设法在每种语言中创建一个工作版本,除了node.js和Javascript.
我知道我的问题,我知道它与回调有关.我知道我做得不对.我得到了回调的基本概念,但我无法弄清楚如何修复我创建的这个混乱.
这是我的全部代码:
var http = require('http');
var url = require('url');
function expand() {
var short = url.parse('http://t.co/wbDrgquZ');
var options = {
host: short.hostname,
port: 80,
path: short.pathname
};
function longURL(response) {
console.log(response.headers.location);
}
http.get(options, longURL);
}
function start() {
function onRequest(request, response) {
console.log("Request received.");
response.writeHead(200, {
"Content-Type": "text/plain"
});
response.write("Hello World");
expand();
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
start();
Run Code Online (Sandbox Code Playgroud)
服务器启动,当发出请求时,它调用expand函数,该函数返回终端中的扩展URL.我试图让它在浏览器中打印.
任何帮助表示赞赏.提前致谢.