如何使用http responce对象在node.js中呈现html页面?

时间:2016-03-31 13:23:35

标签: node.js http

这是我的js文件代码:

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页面上找到结果.....

1 个答案:

答案 0 :(得分:1)

您遇到的问题是connection.query是异步的,您应该在response.end()的回调函数中调用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
            }
        });
    }
});