node.jsサーバーを作成しました。
リクエストからHTTPPOST変数とGET変数を抽出できます。
これらの変数をサーバー上のjsスクリプトに渡して実行したいと思います。
PHPでスクリプトを実行するには、@ www.example.com / path / file.php?variable = valueでそれをポイントします。
<?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 );
}
要約すると、私が達成したかったのは、PHPのようなnode.jsを使用することです。www.example.com/path/file.php?variable=valueの
ようなPHPファイルをnode.jsで実行するにはwww.example.com/path/file.js?variable=value私が思いついた解決策は、要求されたJavaScriptをモジュールに入れ、関数に含めます。例えばrequire
http.createServer(function(req,res){
var myPath=url.parse(req.url).pathname;//get the url
var fullPath=path.join(process.cwd(),myPath);//get the working dir & join it with current working dir
require(fullPath).content(req,res);//this is where the requested script is executed as a module. make sure to end the response (response.end()) in the module
});
徹底的にテストされていませんが、このソリューションは私にとってはうまく機能し、動的ページにも使用できます。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加