node.js发送css文件 [英] node.js sending css files

查看:117
本文介绍了node.js发送css文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得一个node.js服务器来发送css文件。我正在修改此服务器:

I'm trying to get a node.js server to send css files. I'm modifying this server here:

http://github.com/LearnBoost/Socket.IO-node/blob/master/test/server.js

我在做什么有什么问题:

What's wrong with what I'm doing:

server = http.createServer(function(req, res){
    // your normal server code
    var path = url.parse(req.url).pathname;
    switch (path){
        case '/':
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.write('<h1>Welcome. Try the <a href="/chat.html">chat</a> example.</h1>');
            res.end();
            break;

        default:
            if (/\.(js|html|swf)$/.test(path)){
                try {
                    var swf = path.substr(-4) === '.swf';
                    res.writeHead(200, {'Content-Type': swf ? 'application/x-shockwave-flash' : ('text/' + (path.substr(-3) === '.js' ? 'javascript' : 'html'))});
                    res.write(fs.readFileSync(__dirname + path, swf ? 'binary' : 'utf8'), swf ? 'binary' : 'utf8');
                    res.end();
                } catch(e){ 
                    send404(res); 
                }               
                break;
            }
            else if (/\.(css)$/.test(path)){
                    res.writeHead(200, {'Content-Type': 'text/css'});
                    res.end();
                    break;
            }

            send404(res);
            break;
    }
});

谢谢。

推荐答案

你只是为css请求编写一个响应头。

You're only writing a response header for css requests, for one.

我想象如果你调用 curl -I http://your-server/some-file.css ,你会得到一个内容长度为0的200状态。你可以放弃:

I'd imagine if you call curl -I http://your-server/some-file.css, you'd get back a 200 status with a Content-Length of 0. You could just get away with:

res.write(fs.readFileSync(__dirname + path, 'utf8'));

但是。)不要重复自己,和b。这些方法意味着同步。它可能不是这个版本,但在Node中,一般来说,你应该只是调用 readFile 并传递一个回调来完成请求。该API不适合直接链接,但文件系统部分应该有所帮助,请查找'fs .readFile'。

But a.) Don't Repeat Yourself, and b.) the 'sync' in both of those methods means synchronous. It probably isn't for this version, but in Node in general, you should be just calling readFile and passing a callback to finish the request later on. The API isn't great for directly linking, but the File System section should help, look for 'fs.readFile'.

这篇关于node.js发送css文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆