简体   繁体   中英

serving up external static files with node.js

I am using node.JS to build a web app with chat functionality. My server is serving up the basic content of the page but i'm running into problems importing external files like jpgs and style sheets. Here is the head of my main page, with the files I want to import:

<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});
  }

This is the chat server I use to serve up the main page and handle messages. I'm stuck on getting it to handle static resources:

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
 });
});

In order to serve static files, do this (I use express, so I add a middleware to do that)

In your main app file, add this middleware:

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

Actually that's it. Your clients will be served the static files hosted in path /public

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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