lrony* 2011-05-21 20:44 采纳率: 0%
浏览 432

使用 node.js 作为一个简单的 web 服务器

I want to run a very simple HTTP server. Every GET request to example.com should get index.html served to it but as a regular HTML page (i.e., same experience as when you read normal web pages).

Using the code below, I can read the content of index.html. How do I serve index.html as a regular web page?

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.

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

转载于:https://stackoverflow.com/questions/6084360/using-node-js-as-a-simple-web-server

  • 写回答

25条回答 默认 最新

  • 乱世@小熊 2011-05-21 20:57
    关注

    Edit:

    Node.js sample app Node Chat has the functionality you want.
    In it's README.textfile
    3. Step is what you are looking for.

    step1

    • create a server that responds with hello world on port 8002

    step2

    • create an index.html and serve it

    step3

    • introduce util.js
    • change the logic so that any static file is served
    • show 404 in case no file is found

    step4

    • add jquery-1.4.2.js
    • add client.js
    • change index.html to prompt user for nickname

    Here is the server.js

    Here is the util.js

    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制