0

.css ファイルを node.js (express ではない) コードに追加するにはどうすればよいですか? 私は簡単な初心者コードをやっています。私は次のことを試しましたが、うまくいきません:

    function start(response) {
    console.log("Request Handler start was called");
    var body = '<html>' + 
               '<head>' +             
               '<link href="style.css" rel="stylesheet" type="text/css">' +
           '</head>' +
           '<body >' +
           '<center><h1>Hello World</h1></center>' +
           '<marquee>Welcome!!!</marquee>'+
           '<br>'+
           '<form action="/upload" method="post">' +
           '<textarea name="text" rows="8" cols="40" ></textarea>' +
           '<input type="submit" value="submit text" />' +
           '</form>' +
           '</body>' +
           '</html>';
    response.writeHead(200,{'Content-Type': 'text/html'});
    response.write(body);
    response.end();
}

私のstyle.cssは次のようになります:

body { margin-left : 10% ; margin-right : 10% ; margin-top: 10% ; margin-bottom : 10%; background : #D8BFD8; }
h1 { font-weight: bold;color : #8A084B;text-align: center;}
marquee { color:#305d7b; }
p {background: #acbeca; width: 700px; color: black;font-style: italic;}
4

2 に答える 2

2

/style.cssノードアプリでルートを定義していないため、これは機能しません。

これには 2 つの方法があります。

  1. css を html ファイルに直接埋め込みます。するとcssが適用されます。

  2. css ファイルの内容をクライアントに出力する新しいルートを作成し/style.css、html ファイルをそのまま保持します。

于 2013-09-02T09:52:16.903 に答える
0

コードがどのように見えるかはわかりませんが、次のようなものが必要です。

var serverHTML = function(res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    var body = '<html>' + 
       '<head>' +             
       '<link href="/style.css" rel="stylesheet" type="text/css">' +
   '</head>' +
   '<body >' +
   '<center><h1>Hello World</h1></center>' +
   '<marquee>Welcome!!!</marquee>'+
   '<br>'+
   '<form action="/upload" method="post">' +
   '<textarea name="text" rows="8" cols="40" ></textarea>' +
   '<input type="submit" value="submit text" />' +
   '</form>' +
   '</body>' +
   '</html>';
    res.end(body + '\n');
}
var serveCSSData = function(res) {
    res.writeHead(200, {'Content-Type': 'text/css'});
    var css = '\
        body { margin-left : 10% ; margin-right : 10% ; margin-top: 10% ; margin-bottom : 10%; background : #D8BFD8; }\
        h1 { font-weight: bold;color : #8A084B;text-align: center;}\
        marquee { color:#305d7b; }\
        p {background: #acbeca; width: 700px; color: black;font-style: italic;}\
    ';
    res.end(css + '\n');
}
var http = require('http');
http.createServer(function (req, res) {
    switch(req.url) {
        case "/style.css": serveCSSData(res); break;
        default: serverHTML(res);
    }   
}).listen(1337, '127.0.0.1');
console.log('Server running at 127.0.0.1:1337/');
于 2013-09-02T09:52:54.997 に答える