首页 > 解决方案 > 如何在 nodejs 上运行时将 Javascript 文件添加到 HTML

问题描述

我创建了简单的 nodeJs 服务器,这是我的 server.js 文件:

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

var server = http.createServer(function(req, resp){
  // Print the name of the file for which request is made.

  console.log("Request for demo file received.");
  fs.readFile("www/index.html",function(error, data){


    var filePath = '.' + req.url;

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

     resp.writeHead(200, { 'Content-Type': contentType });

     resp.end(data, 'utf-8');
  });
});

server.listen(8081, '127.0.0.1');

这是我的 HTML 文件:

<!DOCTYPE html>
<html>
<head>
  <title>Professor Test DApp</title>
  <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
  <link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' rel='stylesheet' type='text/css'>
</head>
<body class="container">
  <h1>A Simple Test Professor DApp</h1>
  <div class="table-responsive">
  </div>
  <a href="#" onclick="apply()" class="btn btn-primary">Apply</a>
</body>
<script src="https://cdn.rawgit.com/ethereum/web3.js/develop/dist/web3.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>

<script  type="text/javascript" src="index112.js"></script>
</html>

这是我的 js 文件:

function apply(){
  console.log("apply in js file called")
}

当我在没有服务器的浏览器中打开它时,它工作正常,但是当我在服务器中运行它时,无法检测到 js 文件。

标签: javascripthtmlnode.js

解决方案


请检查您的 index112.js 文件路径,因为在服务器上运行时,服务器可能无法找到该文件尝试在src 属性中提供文件的绝对或相对路径,这可能会有所帮助。 绝对或相对路径信息


推荐阅读