Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

node.js - 使用node.js作为简单的Web服务器(Using node.js as a simple web server)

I want to run a very simple HTTP server.

(我想运行一个非常简单的HTTP服务器。)

Every GET request to example.com should get index.html served to it but as a regular HTML page (ie, same experience as when you read normal web pages).

(对example.com每个GET请求都应该将index.html提供给它,但是作为常规HTML页面(即,与阅读普通网页时相同的体验)。)

Using the code below, I can read the content of index.html .

(使用下面的代码,我可以阅读index.html的内容。)

How do I serve index.html as a regular web page?

(如何将index.html作为常规网页提供?)

var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end(index);
}).listen(9615);

One suggestion below is complicated and requires me to write a get line for each resource (CSS, JavaScript, images) file I want to use.

(下面的一个建议很复杂,需要我为我想要使用的每个资源(CSS,JavaScript,图像)文件写一个get行。)

How can I serve a single HTML page with some images, CSS and JavaScript?

(如何使用一些图像,CSS和JavaScript提供单个HTML页面?)

  ask by idophir translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use Connect and ServeStatic with Node.js for this:

(您可以将ConnectServeStatic与Node.js一起使用:)

  1. Install connect and serve-static with NPM

    (使用NPM安装connect和serve-static)

     $ npm install connect serve-static 
  2. Create server.js file with this content:

    (使用此内容创建server.js文件:)

     var connect = require('connect'); var serveStatic = require('serve-static'); connect().use(serveStatic(__dirname)).listen(8080, function(){ console.log('Server running on 8080...'); }); 
  3. Run with Node.js

    (使用Node.js运行)

     $ node server.js 

You can now go to http://localhost:8080/yourfile.html

(您现在可以访问http://localhost:8080/yourfile.html)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...