[英]How to link a script file to an html file using nodeJS
I am serving up some html using nodeJS, but I want to be able to call functions that are in a javascript file, which I am trying to link. 我正在使用nodeJS提供一些html,但我希望能够调用javascript文件中的函数,我试图链接它。 However, I am getting the error message Resource interpreted as Script but transferred with MIME type text/html: "http://localhost:8888/index.js"
. 但是,我收到错误消息Resource interpreted as Script but transferred with MIME type text/html: "http://localhost:8888/index.js"
。 I'm not sure what that won't link properly, and need a way to link my file index.js
. 我不确定哪些内容无法正常链接,需要一种方法来链接我的文件index.js
。 What I was trying to do was load the file into the head, as follows: 我试图做的是将文件加载到头部,如下所示:
http = require('http'),
http.createServer(function(req, res) {
var body = '<html>'+
'<head>'+
'<script src="index.js"></script>'+
'<meta http-equiv="Content-Type" content="text/html; '+
'charset=UTF-8" />'+
'</head>'+
'<body>'+
'</body>'+
'</html>';
response.writeHead(200,{"Content-Type":"text/html"});
response.write(body);
response.end();
}
}).listen(8888);
How can I load this javascript file, index.js
, so that all of the functions contained in index.js
will be available on the client side? 如何加载这个javascript文件index.js
,以便index.js
包含的所有函数都可以在客户端使用?
create a new index.html
page rather than hard coding it - include the script files in it and serve the index.html
. 创建一个新的index.html
页面而不是对其进行硬编码 - 在其中包含脚本文件并提供index.html
。
var http = require('http');
var fs = require('fs');
http.createServer(function(req, res) {
if(req.url == '/index.html') {
var file = __dirname + '/index.html'; //this index.html contains script tag
var stat = fs.statSync(file);
res.writeHead(200, {
'Content-Type': 'text/javascript',
'Content-Length': stat.size
});
var readStream = fs.createReadStream(file);
readStream.pipe(res);
// Send default page
}
}).listen(8888);
The request for index.js
is getting the same response as /
. 对index.js
的请求得到与/
相同的响应。
A simple solution that only handles this one case would be: 只处理这种情况的简单解决方案是:
var http = require('http');
var fs = require('fs');
http.createServer(function(req, res) {
// Send index.js
if(req.url == '/index.js') {
var file = __dirname + '/index.js';
var stat = fs.statSync(file);
res.writeHead(200, {
'Content-Type': 'text/javascript',
'Content-Length': stat.size
});
var readStream = fs.createReadStream(file);
readStream.pipe(res);
// Send default page
} else {
var body = '<html>'+
'<head>'+
'<script src="index.js"></script>'+
'<meta http-equiv="Content-Type" content="text/html; '+
'charset=UTF-8" />'+
'</head>'+
'<body>'+
'</body>'+
'</html>';
res.writeHead(200,{"Content-Type":"text/html"});
res.write(body);
res.end();
}
}).listen(8888);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.