如何使用express js创建一个简单的html服务器 [英] How to create a simple html server using express js

查看:122
本文介绍了如何使用express js创建一个简单的html服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在node.js中是新的,我想创建一个简单的express.js静态文件服务器,但是我有一些问题。
我已经安装了express.js 4.2全局如下:

I'm new in node.js I want to create a simple express.js static file server, but I have some issues. I have been installed express.js 4.2 globally like this:

npm install  -g express-generator

我在httpsrv.js中有这个代码:

I have this code in httpsrv.js:

var http = require('http');
var express = require('express');
var app = express();

app.use('/', express.static(__dirname + '/public'));
app.listen(3000, function() { console.log('listening')});

我不知道是否可以,我猜这还不够,但是我无法运行它失败与错误:找不到模块'express'。

I'm not sure is it ok I guess it is not enough, but I cant run it it's failed with error: cannot find module 'express'.

我想创建一个简单的http服务器,可以从特定的文件夹(\publiceg)和我'使用.html语言。我在互联网上发现了许多胡说,我不想使用这个.jade的东西,我不想用express等创建一个空的Web应用程序。我想要可以像Apache一样运行的express.js http服务器,可以从指定的文件夹首先提供静态html页面。
任何人可以帮助我,建议一个很好的文章,这是一步一步解释,因为我是初学者。

I want to create a simple http server which can serve from specific folder("\public" e.g.) and I'm using .html language. I found on the internet a many bullshit, I don't want to use this .jade thing and I don't want to create a empty web app with express etc. I want express.js http server which can operate like Apache and can serve a static html pages first from a specified folder. Can anybody help me on this, suggest a good article which is explain a step by step, because I'm beginner.

推荐答案

如果您只是想从一个名为public的目录中提供静态文件,您可能会遇到一个应用程序像这样:

If you're just trying to serve static files from a directory called "public", you might have luck with an app like this:

var path = require('path');
var express = require('express');

var app = express();

var staticPath = path.join(__dirname, '/public');
app.use(express.static(staticPath));

app.listen(3000, function() {
  console.log('listening');
});

您需要确保Express已安装。您可能会在与上述JavaScript文件相同的目录中运行 npm install express --save 。一旦你准备好了,你将运行 node the_name_of_the_file_above.js 启动你的服务器。

You'll need to make sure Express is installed. You'll probably run npm install express --save in the same directory as the above JavaScript file. Once you're all ready, you'll run node the_name_of_the_file_above.js to start your server.

这篇关于如何使用express js创建一个简单的html服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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