我已經編寫了一個node.js服務器。
我能夠從請求中提取HTTP POST和GET變量。
我想將這些變量傳遞給要執行的服務器上的js腳本。
在PHP執行腳本我只是指向它@ www.example.com/path/file.php?variable=value
如何在node.js服務器中執行javascript
<?php echo "You have ".$_GET['variable'];?>
我想實現與noge.js @ WWW相同.example.com/path/file.njs?variable = value
我的問題是file.njs被作爲文本執行。 我不使用快遞,沒有它的解決方案,將不勝感激。
var sys=require("sys"),
http=require("http"),
path=require("path"),
url=require("url"),
filesys=require("fs"),
mime=require("./node_modules/mime"),
head=require("./node_modules/headers/initreq.njs");//this is used to extract the header
http.createServer(handler).listen(80);//handler function is below
sys.puts("Node Server Running on 80");
function handler(request,response){
var myPath=url.parse(request.url).pathname;//get the url
var ext=myPath.replace(/(.)*\./,'');//get the extension
var fullPath=path.join(process.cwd(),myPath);//get the working dir & join it with current working dir
var mimeResult=mime.lookup(fullPath),acceptExt=['html','njs'];
if(acceptExt.indexOf(ext)!=-1){//only search HTTP header for html|njs files
head.init(request,response,setContent);//head will correctly contain the $_GET AND $_POST variable
} else {setContent();}
function setContent(){
path.exists(fullPath,function(exists){
if(!exists){
response.writeHeader(404, {"Content-Type":"text/plain"});
response.write("404 Not Found:: "+fullPath+"\n");
response.end();
}else{
filesys.readFile(fullPath,"binary",function(err,file){
if(err){
response.writeHeader(500,{"Content-Type":"text/plain"});
response.write(err+"::"+myPath+"\n");
response.end();
}else{
response.setHeader("Content-Type", mimeResult);
response.writeHeader(200);
response.write(file,"binary");//this is the file that i want to execute and pass the $_POST & $_GET variable
response.end();
}
});
}
});
}
sys.puts("Requested:: "+myPath.replace(/(.)*\//,'')+" - "+mimeResult);
}
** XY問題** http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem#answer-66378 – David
好吧@大衛授予我想像一個PHP開發人員。那麼這將如何解決?錯誤地認爲node.js可以像PHP一樣使用 – fredtma