具有node.js的基本Web服务器,并为html文件和资产提供服务 [英] Basic webserver with node.js and express for serving html file and assets

查看:75
本文介绍了具有node.js的基本Web服务器,并为html文件和资产提供服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些前端实验,我想要一个非常基本的网络服务器来快速启动项目并提供文件(一个index.html文件+一些css / js / img文件)。所以我试图做一些与node.js和express,我已经玩过,但我不想使用一个渲染引擎这次,因为我只有一个静态文件,这个代码我得到html文件而不是资产(错误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);

是否有一种简单的方法(如果可能的话,在一个文件中)或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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆