在Web -Browser语言 - Node JS中执行.html



我正在运行一个程序,该程序验证 .html文件(index.html),然后在Web-Browser上运行程序。(localhost:port/index.html)

我的程序知道我要提供正确的文件,但是我无法在Web-Browser中执行.html文件(只是尝试显示日期)。

我一直在网上寻找参考文献,但也许我不是朝着正确的方向寻找,或者我只是在忽略某些内容。

也响应。端子也不会在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

另外,我相信响应。我可以理解响应。

希望这会有所帮助。

编辑:只需意识到我的响应假设您正在使用Express Framework。

如果您将函数用作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}`)
})

最新更新