【问题标题】:serving up external static files with node.js使用 node.js 提供外部静态文件
【发布时间】:2015-07-09 03:20:46
【问题描述】:

我正在使用 node.JS 构建具有聊天功能的 Web 应用程序。我的服务器正在提供页面的基本内容,但在导入 jpg 和样式表等外部文件时遇到问题。这是我主页的标题,其中包含我要导入的文件:

<head>
<meta charset="utf-8"/>
 <link rel="stylesheet" type="text/css" href="stylesheets/main.css" />
 <link href='http://fonts.googleapis.com/css?family=Alegreya+Sans' rel='stylesheet' type='text/css'>
 <link href='http://fonts.googleapis.com/css?family=Slabo+27px' rel='stylesheet' type='text/css'>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
 <script src="/socket.io/socket.io.js"></script>
 <script type ="text/javascript">

  var socketio = io.connect();
  socketio.on("message_to_client",function(data) {
     //Append an HR thematic break and the escaped HTML of the new message
     document.getElementById("chatBox").appendChild(document.createElement("hr"));
     document.getElementById("chatBox").appendChild(document.createTextNode(data['message']));
  });

  function sendMessage(){
     var msg = document.getElementById("message_input").value;
     socketio.emit("message_to_server", {message:msg});
  }

这是我用来提供主页和处理消息的聊天服务器。我一直坚持让它处理静态资源:

var http = require("http"),
socketio = require("socket.io"),
fs = require("fs"),
mime = require('mime');

var url = 'home.html';


var app = http.createServer(function(req, resp){

fs.readFile(url, function(err, data){

    if(err) return resp.writeHead(500);

    var mimeType = mime.lookup(url);
    resp.setHeader('Content-Type', mimeType);
    resp.writeHead(200);
    resp.end(data);
    });
});
app.listen(3456);

var io = socketio.listen(app);
io.sockets.on("connection", function(socket){
// This callback runs when a new Socket.IO connection is established.

socket.on('message_to_server', function(data) {
    // This callback runs when the server receives a new message from the client.

    console.log("message: "+data["message"]); // log it to the Node.JS output
    io.sockets.emit("message_to_client",{message:data["message"] }) // broadcast the message to other users
 });
});

【问题讨论】:

    标签: javascript node.js socket.io


    【解决方案1】:

    为了提供静态文件,请执行此操作(我使用 express,所以我添加了一个中间件来执行此操作)

    在你的主应用文件中,添加这个中间件:

    app.use(express.static(__dirname + '/public')); //the argument is the location of the root directory with static files
    

    其实就是这样。将为您的客户提供路径 /public 中托管的静态文件

    【讨论】:

      猜你喜欢
      • 2013-03-06
      • 2013-10-19
      • 2014-07-20
      • 2017-05-18
      • 2011-06-05
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 2014-11-24
      相关资源
      最近更新 更多