【问题标题】:How to run a html file (which is having external js file) through nodejs如何通过nodejs运行html文件(具有外部js文件)
【发布时间】:2017-11-21 19:38:59
【问题描述】:

我想通过nodejs运行index.html文件(其中包含外部js文件client.js)

这是我的 index.html 代码:

<!DOCTYPE html>
<html>
<head>
  <title> WEBCAM </title>
</head>
<body>
  <div>
    <button id='request'>Request Camera</button>
    <script type="text/javascript" src="client.js"></script>
</body>
</html>

这是我通过nodejs运行这个文件的服务器代码

var http= require('http');
var fs= require('fs');
var file= fs.readFile("./public/index.html", function(error,html) {
  if (error) {
    throw error;
  } else {
    var server= http.createServer(function(req,rspn) {
      rspn.writeHead(200,{"Content-Type":"text/html"});
      rspn.write(html);
      rspn.end();
    });
    server.listen(8000);
  }
});

如果我将外部 js 文件直接复制到 html 文件中并通过 nodejs 运行它,那么它可以正常工作,但如果我将 js 文件作为外部文件则不能。 我的外部文件(client.js)如下 -

function requestVideo() {       
  if (hasGetUserMedia()) {                
    navigator.getUserMedia({video: true,audio:false}, function(localMediaStream) {       
      reqBtn.style.display = 'none';        
      video.src = window.URL.createObjectURL(localMediaStream);        
      startBtn.removeAttribute('disabled');        
    },errorCallback);       }       
    else{        
      alert("getUserMedia() is not supported in your system");       
    }      
} 

【问题讨论】:

  • “运行 HTML 文件”是什么意思?
  • 你的服务器只提供HTML文件,不提供JS文件,那么客户端应该如何获取JS文件呢?
  • 我正在使用 node 运行 server.js 来运行服务器代码。现在,在我在 localhost:8000 中打开 html 文件之后,html 文件不包括 client.js 文件,而是在 client.js 中复制 index.html 的相同内容
  • @tkausl 在我的 html 文件中,我包含 client.js 文件 并尝试从客户端加载内容.js 但它没有发生
  • 是的,因为您的 node.js 服务器不提供 JS 文件。

标签: javascript jquery html node.js


【解决方案1】:

如果你想提供像 html 或 js 文件这样的文件,你可以创建一个静态文件服务器,如下所示:

var http = require('http');
var fs = require('fs');
var path = require('path');

http.createServer(function (request, response) {

    var filePath = '.' + request.url;

    var extname = path.extname(filePath);
    var contentType = 'text/html';
    if(extname ==  '.js'){
            contentType = 'text/javascript';
    }

    fs.readFile(filePath, function(error, content) {
        response.writeHead(200, { 'Content-Type': contentType });
        response.end(content, 'utf-8'); 
    });

}).listen(8000);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    相关资源
    最近更新 更多