javascript - 如何在 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 文件。
解决方案
请检查您的 index112.js 文件路径,因为在服务器上运行时,服务器可能无法找到该文件尝试在src 属性中提供文件的绝对或相对路径,这可能会有所帮助。 绝对或相对路径信息
推荐阅读
- python - if-else 语句缺少返回值
- .htaccess - htaccess 重写 - 从 url 中删除最后一部分
- r - 在 R 中使用 as.numeric 后使用 if 语句时,将因子转换为数值变量会出错
- css - 语义ui删除css中的列卡高度
- spring-boot - 如何在 Spring Data Mongo DB 中使用带下划线的数据模型变量?
- angular - 如果我添加导入,则不会呈现任何内容
- pyspark - 比较两个数据帧的行以找到匹配的列数 1
- python - 熊猫取最接近第二个的值并进行插值
- scala - 自动生成数组(字符串)
- ivy - 使用 ivy.xml 在 test 和 prod 中具有不同的依赖关系