一直在开发托管在 OpenShift 上的 Node.js RESTful Web 服务。目前我已经通过简单的方法调用等取得了成功,但似乎无法通过异步回调获得 http 响应。
这是我目前拥有的:
var http = require("http");
var url = require("url"); // used to get the requested method name as well as parameters
var util = require("util");
// global variables
// router function
function route(pathname, query, callbackFunc) {
//return executeMethod(pathname, query);
var returnValue;
switch (pathname.toUpperCase()) {
case "/ADD":
returnValue = add(query['num1'], query['num2']);
//util.process.nextTick(function() {
//callbackFunc(null, returnValue);
//});
break;
case "/ADDASYNC":
//addAsync(query['num1'], query['num2'], callback);
break;
default:
returnValue = "method not found";
break;
}
//return returnValue;
//return "Route for request " + pathname + " complete, query: " + query;
}
// actual web method execution
function add(num1, num2){
//return "add method called with values: " + num1 + " " + num2;
return parseFloat(num1) + parseFloat(num2);
}
function addAsync(num1, num2, callback){
//util.process.nextTick(function(){
// var value = parseFloat(num1) + parseFloat(num2);
// util.process.nextTick(function(){
// callback(value);
// });
//});
}
// main request handler for server
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
var query = url.parse(request.url, true).query;
console.log("Request for " + pathname + " Recieved");
response.setTimeout(500);
var myCallback = function(err, data){
if(err){
response.writeHead(200, {"Content-Type": "text/plain"});
response.write('an error occured with requested method');
response.end();
}else{
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(data);
response.end();
}
}
//var finalValue = route(pathname, query);
//var finalValue = 0;
(function(){route(pathname, query, myCallback)})();
response.writeContinue();
//process.nextTick(myCallback(null, 'hello world'));
setTimeout(function(){
myCallback(null, "hello world");
}, 15);
//myCallback();
//response.writeHead(200, {"Content-Type": "text/plain"});
//response.write("Hello World. You requested: " + pathname + " with type " + pathname.type + ", value: " + finalValue);
//response.end();
}
// create the server and signal console of start
http.createServer(onRequest).listen(8080, process.env.OPENSHIFT_INTERNAL_IP);
// for debug
//http.createServer(onRequest).listen(process.env.PORT, process.env.IP);
console.log("Server has started. Listening to port: " + 8080 + " ip address: " + process.env.OPENSHIFT_INTERNAL_IP);
如果我直接在 onRequest 方法中调用 myCallback 方法,那么我会毫无问题地得到响应;但是,使用 process.nextTick 或 setTimeout 在 onRequest 或路由方法中调用 myCallback 函数似乎不起作用。我正在使用 Cloud9 IDE 和直接 git push 到 OpenShift 来处理这个项目,所以我在调试时遇到了一些困难,但尝试了很多不同的方法,但都没有成功,包括设置 request.setTimeout 函数以提供一些时间要触发的计时器/进程事件。我当前的 OpenShift 应用程序正在运行 Node.js 0.6。是否有任何明显可能导致我可能遗漏的问题?