将文档根目录设置为 Node.js http 服务器?
我只是在本地计算机上使用 socket.io 设置了一个基本的 Node.js 服务器。有没有办法设置文档根目录以便可以包含其他文件。 IE。下面我有一个带有背景图像的 DIV。图像的路径相对于服务器的位置,但这不起作用。有什么想法吗?谢谢!
var http = require('http'),
io = require('socket.io'), // for npm, otherwise use require('./path/to/socket.io')
server = http.createServer(function(req, res){
// your normal server code
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<div style="background-image:url(img/carbon_fibre.gif);"><h1>Hello world</h1></div>');
});
server.listen(8080);
// socket.io
var socket = io.listen(server);
I just setup a basic node.js server with socket.io on my local machine. Is there a way to set a document root so that you can include other files. Ie. Below I have a DIV with a a background image. The path the image is relative to the location of the server, however this is not working. Any ideas? Thanks!
var http = require('http'),
io = require('socket.io'), // for npm, otherwise use require('./path/to/socket.io')
server = http.createServer(function(req, res){
// your normal server code
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<div style="background-image:url(img/carbon_fibre.gif);"><h1>Hello world</h1></div>');
});
server.listen(8080);
// socket.io
var socket = io.listen(server);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 Express 或 连接。示例: https://github.com/spadin/simple-express-static-server, http://senchalabs.github.com/connect/middleware-static.html< /a>
Use Express or Connect. Examples: https://github.com/spadin/simple-express-static-server, http://senchalabs.github.com/connect/middleware-static.html
对于背景图像样式,浏览器将创建一个全新的 HTTP 请求到您的服务器,路径为 *img/carbon_fibre.gif*,这个请求肯定会命中您的匿名函数,但您的响应函数只写回一个 div 与 ContentType: text/html 无关的 req.pathname 导致图像无法正常显示。
你可以在你的函数中添加一些代码,例如:
我对nodejs不太熟悉,所以上面的代码只演示了一个逻辑,而不是实际可运行的代码块。
For the background-image style, browser will create a entirely new HTTP Request to your server with path *img/carbon_fibre.gif*, and this request will certainly hit your anonymous function, but your response function only write back a div with ContentType: text/html regardless the req.pathname so that the image cannot be properly displayed.
You may add some code to your function like:
I'm not very familiar with nodejs, so the code above only demonstrates a logic but not the actual runnable code block.