Javascript 在web浏览器中执行.HTML-节点js
我正在运行一个程序,该程序验证Javascript 在web浏览器中执行.HTML-节点js,javascript,html,node.js,Javascript,Html,Node.js,我正在运行一个程序,该程序验证.html文件(index.html),然后在web浏览器上运行该程序(localhost:port/index.html) 我的程序知道我要求的是正确的文件,但我无法在web浏览器中执行.html文件(只是试图显示日期) 我一直在网上寻找推荐人,但可能我没有朝正确的方向看,或者我只是忽略了一些东西 此外,response.end不会打印到web浏览器上,即使带有response.end的其他功能工作正常 function doHTML(http_request,
.html
文件(index.html
),然后在web浏览器上运行该程序<代码>(localhost:port/index.html)
我的程序知道我要求的是正确的文件,但我无法在web浏览器中执行.html
文件(只是试图显示日期)
我一直在网上寻找推荐人,但可能我没有朝正确的方向看,或者我只是忽略了一些东西
此外,response.end不会打印到web浏览器上,即使带有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');
});
}
我对NodeJS也相当陌生,但我相信以下链接可能会帮助您: 另外,我相信response.end(“…text and stuff…”)会将文本发送到您的web/桌面客户端,以便您可以在那里处理响应:打印、解析等。因此,我可以理解response.end不会像console.log那样直接打印到web浏览器上 希望这有帮助
编辑:刚刚意识到我的回答假设您使用的是Express框架 如果您将函数用作node.js的请求处理程序,那么您应该使用
http\u request.url
而不是http\u 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}`)
})