我创建了一个简单的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文件。
答案 0 :(得分:0)
请检查您的index112.js文件路径,因为在服务器上运行时,可能无法找到文件,尝试在 src属性中提供文件的绝对或相对路径,这可能救命。 Absolute or Relative Path Info
答案 1 :(得分:0)
我认为您需要提供静态文件。创建public
文件夹,并将index112.js
移到public
文件夹中。按照以下说明使用express.static
内置的中间件功能。
app.use(express.static(path.join(__dirname, 'public')));