【问题标题】:How to get a HTML page in nodejs?如何在 nodejs 中获取 HTML 页面?
【发布时间】:2013-04-18 09:25:36
【问题描述】:

test.html

<html>
    <head>
        <title>Test Page</title>
    </head>
    <body> This is the body</body>
</html>

如何修改:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

返回上面的test.html

【问题讨论】:

标签: html node.js


【解决方案1】:

这是一个简单的流式静态服务器示例

var basepath = '/files'

http.createServer(function (req, res) {
  if (req.method !== 'GET') {
    res.writeHead(400);
    res.end();
    return;
  }
  var s = fs.createReadStream(path.join(basepath, req.path));
  s.on('error', function () {
    res.writeHead(404);
    res.end();
  });
  s.once('fd', function () {
    res.writeHead(200);
  });
  s.pipe(res);
});

在实践中你应该使用 express.static:http://runnable.com/UWw3g0PKxoAWAA6K

或者像https://github.com/jesusabdullah/node-ecstatic这样的专用静态模块

【讨论】:

    猜你喜欢
    • 2018-01-05
    • 2015-06-04
    • 2021-02-11
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 2021-11-13
    • 2012-03-07
    相关资源
    最近更新 更多