具有node.js的基本Web服务器,并为html文件和资产提供服务 [英] Basic webserver with node.js and express for serving html file and assets
问题描述
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);
是否有一种简单的方法(如果可能的话,在一个文件中)或Express需要使用一个视图和渲染引擎?你可以使用 这样一个在node.js中的解决方案 (链接不再有效)
总结,安装连接与 npm install connect
。
然后将该代码粘贴到与您的HTML / CSS / JS文件相同的文件夹中的名为 server.js
的文件。
var util = require('util'),
connect = require('connect'),
port = 1337;
connect.createServer(connect.static(__ dirname))。listen(port);
util.puts('Listening on'+ port +'...');
util.puts('按Ctrl + C停止');
现在导航到终端中的该文件夹,然后运行 node server.js
,这将给你一个临时的Web服务器在 http:// localhost:1337
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 ?
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
这篇关于具有node.js的基本Web服务器,并为html文件和资产提供服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!