如何在没有第三方库的情况下以编程方式在服务器上生成Html?

时间:2015-01-19 21:22:54

标签: javascript html node.js server

我问了一个类似的问题,但在它被复制之前我忘了提及我想要了解如何在不使用第三方库的情况下这样做。

How can I dynamically generate Html content with Node.js?

那么,我如何使用Node.js以编程方式在服务器端生成Html内容? (我不是指发送硬编码的Html,我的意思是像在客户端那样生成它)。

(我没有反对第三方库。我更喜欢在了解它之前了解Node.js。)

2 个答案:

答案 0 :(得分:0)

var http = require('http');
var html = '<!doctype html><html><body><h1>Hello, World!</h1></body></html>';

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end(html);
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

答案 1 :(得分:0)

创建您的网络服务器,监听您想要的任何端口,然后让它以您想要的任何html响应您想要的任何端点的请求。

// Include the HTTP Node library
// http://nodejs.org/docs/latest/api/http.html
var http = require('http');

// define the IP and port number
var localIP = "127.0.0.1"; // 127.0.0.1 is used when running the server locally
var port = 8080; // port to run webserver on

function sayHello(req, res) {

    console.log("We've got a request for " + req.url);

    // HTTP response header - the content will be HTML MIME type
    res.writeHead(200, {'Content-Type': 'text/html'});

    // Write out the HTTP response body
    res.write('<html><body>' +
    '<h1>Hello Dynamic World Wide Web<h1>'+
    '</body></html>');

    // End of HTTP response
    res.end();

}

/************************/
/*  START THE SERVER    */
/************************/

// Create the HTTP server
var server = http.createServer(sayHello);

// Turn server on - now listening for requests on localIP and port
server.listen(port, localIP);

// print message to terminal that server is running
console.log('Server running at http://'+ localIP +':'+ port +'/');

上述代码取自https://gist.github.com/johnschimmel/1759465