这真是个奇怪的问题。我刚刚在我的系统 (Fedora) 上安装了 Node.JS。
我在/var/www/mirror/ 中有三个文件:
- server.js
- 客户端.js
- index.html
文件 server.js 是我通过 CLI 调用的文件:node server.js
.
基本上,它返回 index.html。
var
http = require('http'),
io = require('socket.io'),
fs = require('fs');
http.createServer(function(request, response) {
fs.readFile(__dirname + '/index.html', function(error, data) {
if (error) {
result.writeHead(500);
console.log('Error: Could not read index.html.');
}
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(data);
});
}).listen(1337, '127.0.0.1');
console.log('Server is running.');
一切都按预期工作,任何地方都不会抛出错误。
在 index.html 中,我有简单的 HTML5 结构(没有什么不必要的,真的!)和 <script />
这指向已经提到的 client.js。
这行代码看起来像这样(Ctrl + U;来自浏览器):
<script src="client.js"></script>
通过将光标移动到 client.js
,我得到了实际位置:http://127.0.0.1:1337/client.js
.
似乎是正确的,对吧?
问题:
通过打开该链接,它会打开想要的文件,但内容为 server.js
应该返回。
这不允许我包含任何内部脚本和样式表!
我猜任何经过 http://127.0.0.1:1337/
的东西(还有 http://127.0.0.1:1337/client.js
、 http://127.0.0.1:1337/a/b/c
等)通过 server.js 处理 - 并且 server.js 返回 index.html(参见以上)。
我该如何解决?感谢任何建议!
最佳答案
查看 req.url
以了解用户请求的 url。从那里,您必须有一些代码来决定是提供 index.html 还是 client.js。
此外,由于我猜测 index.html
不会经常更改,您应该只读取一次,并将缓冲区存储在变量中,而不是在每次请求时都读取它.
有一些模块可以使服务静态文件更容易一些。查看 filed
以获得非常好的独立静态文件
关于linux - 内部脚本和样式表总是指向索引文件 (Node.JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8376952/