簡體   English   中英

使用node.js提供外部靜態文件

[英]serving up external static files with node.js

我正在使用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
 });
});

為了提供靜態文件,請執行此操作(我使用express,因此我添加了一個中間件來執行此操作)

在您的主應用程序文件中,添加以下中間件:

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

其實就是這樣。 將向您的客戶提供路徑/public托管的靜態文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM