2016-03-31 16 views
0

これが私のjsファイルのコードです:http応答オブジェクトを使用してnode.jsにHTMLページをレンダリングする方法は?

fs.readFile(__dirname+'/product_list.html',function(error,productForm){ 
    if(error){ 
     response.write("error in getting file"+error); 
    }else{ 
      connection.query("select * from products",function(err,result){ 
      if(err){ 
       console.log("In funciton errr"); 
      }else{ 
       response.writeHead(200, "OK", {'Content-Type': 'text/html'}); 
       response.write(productForm,{result:result}); 

       } 
     }); 
    response.end(); 
    } 
}); 

私はproduct_list.htmlページになりたい.....

+0

の機能とクリーナー –

+0

私はproduct_list.htmlページにレンダリングけど...トンに結果オブジェクトを取得していません帽子のページ – Hemant

答えて

1

あなたは持っている問題はconnection.queryが非同期であるということです、あなたはコールバック内response.end()を呼び出す必要がありますあなたは `ejs`か、それはこのように速くなり、他の一つとして、テンプレートエンジンを使用することができますconnection.query

fs.readFile(__dirname+'/product_list.html',function(error,productForm){ 
    if(error){ 
     response.write("error in getting file"+error); 
     response.end(); //finish here 
    }else{ 
     connection.query("select * from products",function(err,result){ 
      if(err){ 
       console.log("In funciton errr"); 
       response.end(); //finish here 
      }else{ 
       response.writeHead(200, "OK", {'Content-Type': 'text/html'}); 
       response.write(productForm,{result:result}); 
       response.end(); //finish here 
      } 
     }); 
    } 
}); 
+0

答えに感謝.....このコードを追加した後...同じ問題は、彼らの.....レンダリングのページですが、product_list.htmlページ – Hemant

+0

の結果オブジェクトを取得していません。 .without任意のフレームワークを使用する... – Hemant

+0

'productForm'と' {result:result} 'は何ですか?任意のテンプレートエンジンを使用していますか?それは 'response.render(productForm、{result:result})' –

関連する問題