[英]Executing an .HTML in a web-browser - node js
我正在運行一個驗證.html
文件( index.html
)的程序,然后在Web瀏覽器上運行該程序。 (localhost:port/index.html)
。
我的程序知道我要的是正確的文件,但無法在Web瀏覽器中執行.html
文件(只是試圖顯示日期)。
我一直在網上尋找參考,但也許我沒有朝正確的方向看,或者只是在俯視一些東西。
此外,即使其他具有response.end的功能完美運行,response.end也不會打印到Web瀏覽器上。
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');
});
}
我對NodeJS也很陌生,但是我相信以下鏈接可以幫助您:
https://expressjs.com/en/api.html#res.render
另外,我相信response.end('.. text and stuff ..')會將文本發送到您的Web /桌面客戶端,以便您可以在那里處理響應:將其打印,解析等。這對我來說是可以理解的該response.end不會像console.log那樣直接打印到Web瀏覽器上。
希望這可以幫助。
編輯:剛意識到我的回答假設您正在使用Express框架。
如果您將函數用作node.js的請求處理程序,則似乎應該使用http_request.url
而不是http_request
。 以下功能對我有用(服務器骨架從此處開始 ):
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}`)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.