2017-03-10 33 views
0

我正在運行一個程序來驗證.html文件(index.html),然後在Web瀏覽器上運行該程序。 (localhost:port/index.html)在Web瀏覽器中執行.HTML - 節點js

我的程序明白我要求正確的文件,但我不能在網絡瀏覽器中執行.html文件(只是試圖顯示日期)。

我一直在網上尋找參考,但也許我不是在正確的方向看,或者我只是俯瞰一些東西。

此外response.end不會打印到網絡瀏覽器上,即使其他功能與response.end它完美地工作。

function doHTML(http_request, response) 
{ 
    // Read the requested file content from file system 
    fs.readFile('MYHTML/' + http_request, function (err, data) { 
    console.log('Hey youre in the HTML function'); 
    response.end('Hey you got it working'); 

    }); 
} 

回答

0

我是相當新的作爲的NodeJS很好,但我相信下面的鏈接可以幫助你:

https://expressjs.com/en/api.html#res.render

而且,我相信到Response.End(」 ..文字和東西......「)將文本發送到您的網絡/桌面客戶端,以便您可以在那裏處理響應:打印它,解析它等。因此,我可以理解response.end不會直接打印到網頁上,瀏覽器作爲console.log會做。

希望這會有所幫助。

編輯:只是意識到我的迴應假設您使用Express框架。

0

如果你正在使用你的函數作爲node.js的請求處理程序,它看起來應該使用http_request.url而不是http_request。以下函數適用於我(服務器骨架從here):

const fs = require('fs') 
const http = require('http') 
const port = 3000 

const requestHandler = (http_request, response) => { 
    console.log(http_request.url) 
    fs.readFile('MYHTML/' + http_request.url, function (err, data) { 
    if (! err){ 
     console.log('Hey youre in the HTML function.'); 
     response.write(data); 
     response.write('Hey you got it working'); 
     response.end(); 
    } else { 
     response.end("File not found."); 
    } 
    }); 
} 

const server = http.createServer(requestHandler) 

server.listen(port, (err) => { 
    if (err) { 
    return console.log('something bad happened', err) 
    } 

    console.log(`server is listening on ${port}`) 
})