繁体   English   中英

在localhost中使用Node.JS的CSS / JS

[英]CSS/JS with Node.JS in localhost

我正在发现Node.js,我在localhost中的.css和.js文件有点问题。 我尝试了很多东西,但在我的情况下不起作用(例如http://ericsowell.com/blog/2011/5/6/serving-static-files-from-node-js

我的文件是这样的:

mysite的/ app.js

mysite的/ index.html的

mysite的/的package.json

mysite / css / my .css文件

mysite / js / my .js文件

mysite / node_modules / 所有node.js模块

我在app.js中试过这个:

var app = require('express')(),
http = require('http');
fs = require('fs');
path = require('path');
imtesting = function (req, res) {

    var filePath = '.' + request.url;
    if (filePath == './')
        filePath = './index.htm';

    var extname = path.extname(filePath);
    var contentType = 'text/html';
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
    }

    path.exists(filePath, function(exists) {

        if (exists) {
            fs.readFile(filePath, function(error, content) {
                if (error) {
                    response.writeHead(500);
                    response.end();
                }
                else {
                    response.writeHead(200, { 'Content-Type': contentType });
                    response.end(content, 'utf-8');
                }
            });
        }
        else {
            response.writeHead(404);
            response.end();
        }
    });

}

server = http.createServer(app, imtesting),
io = require('socket.io').listen(server),
ent = require('ent'), // Permet de bloquer les caractères HTML (sécurité équivalente à htmlentities en PHP)


// Chargement de la page index.html
app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});



io.sockets.on('connection', function (socket, pseudo) {
    // Dès qu'on nous donne un pseudo, on le stocke en variable de session et on informe les autres personnes
    socket.on('nouveau_client', function(pseudo) {
        pseudo = ent.encode(pseudo);
        socket.set('pseudo', pseudo);
        socket.broadcast.emit('nouveau_client', pseudo);
    });

    // Dès qu'on reçoit un message, on récupère le pseudo de son auteur et on le transmet aux autres personnes
    socket.on('message', function (message) {
        socket.get('pseudo', function (error, pseudo) {
            message = ent.encode(message);
            socket.broadcast.emit('message', {pseudo: pseudo, message: message});
        });
    }); 
});

server.listen(8080);

但结果仍然存在

GET http://localhost:8080/css/bootstrap.min.css 404 (Not Found) localhost/:14
GET http://localhost:8080/css/site-style.css 404 (Not Found) localhost/:17
GET http://localhost:8080/css/spray-style.css 404 (Not Found) localhost/:21
GET http://localhost:8080/js/bootstrap.min.js 404 (Not Found) localhost/:98
GET http://localhost:8080/js/spray-reader.js 404 (Not Found) localhost/:99

我尝试了很多解决方案......

谢谢大家,对不起,如果我的英语让你的眼睛流血了。

你做的不仅仅是必要的。 使用express,您可以通过中间件设置静态路由,这些中间件将从设置路径提供内容:

app.use('/js', express.static(__dirname, + '/js')));
app.use('/css', express.static(__dirname, + '/css')));

你可以在这里阅读更多相关内容: http//expressjs.com/faq.html#multiple-statics

app.use(express.static(path.join(__dirname, 'public')));

为什么在使用原始node.js时太容易使用其他框架

看一看 :

<!DOCTYPE HTML>
<html>

<head>
    <link rel="stylesheet" href="css/style.css" />
</head>

</html>

**在node.js文件中:**

var url = require('url');
var pathnaame = url.parse(req.url,true)
var filepath = "./"

if(fs.existsSync(filepath+pathname)){
        res.end(fs.readFileSync(filepath+pathname));
    }

浏览器发送获取请求以获取css / js文件; **在这种情况下:**会产生结果

pathname="css/style.css"
filepath = "./"
filepath + pathname = "./css/style/css"

fs.readFileSync将返回true并将数据提供给响应。

您也可以使用异步函数以异步方式执行此操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM