Basic webserver with node.js and express for serving html file and assets

江枫思渺然 提交于 2019-12-31 08:05:09

问题


I'm making some frontend experiments and I'd like to have a very basic webserver to quickly start a project and serve the files (one index.html file + some css/js/img files). So I'm trying to make something with node.js and express, I played with both already, but I don't want to use a render engine this time since I'll have only a single static file, with this code I get the html file but not the assets (error 404):

var express = require('express'),
    app = express.createServer();

app.configure(function(){
  app.use(express.static(__dirname + '/static'));
});

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

app.listen(3000);

Is there a simple way to do it (in one file if possible) or Express requires the use of a view and render engine ?


回答1:


You could use a solution like this in node.js (link no longer works), as I've blogged about before.

The summarise, install connect with npm install connect.

Then paste this code into a file called server.js in the same folder as your HTML/CSS/JS files.

var util = require('util'),
    connect = require('connect'),
    port = 1337;

connect.createServer(connect.static(__dirname)).listen(port);
util.puts('Listening on ' + port + '...');
util.puts('Press Ctrl + C to stop.');

Now navigate to that folder in your terminal and run node server.js, this will give you a temporary web server at http://localhost:1337




回答2:


I came across this because I have a similar situation. I don't need or like templates. Anything you put in the public/ directory under express gets served as static content (Just like Apache). So I placed my index.html there and used sendfile to handle requests with no file (eg: GET http://mysite/):

app.get('/', function(req,res) {
  res.sendfile('public/index.html');
});



回答3:


Following code worked for me.

var express = require('express'),
  app = express(),
  http = require('http'),
  httpServer = http.Server(app);

app.use(express.static(__dirname + '/folder_containing_assets_OR_scripts'));

app.get('/', function(req, res) {
  res.sendfile(__dirname + '/index.html');
});
app.listen(3000);

this loads page with assets



来源:https://stackoverflow.com/questions/9443840/basic-webserver-with-node-js-and-express-for-serving-html-file-and-assets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!