[英]How to add a Javascript file to HTML while running on nodejs
我創建簡單的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屬性中給出文件的絕對路徑或相對路徑,這可能會有所幫助。 絕對或相對路徑信息
我認為你需要提供靜態文件。 創建public
文件夾,移動index112.js
在public
文件夾中。 使用express.static
內置中間件功能,如下所示。
app.use(express.static(path.join(__dirname, 'public')));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.