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

How can I programatically generate Html on the server, without a third party library?

本文关键字:编程 Html 服务器 方式生 第三方 情况下      更新时间:2023-09-26

我问了一个类似的问题,但在它作为副本关闭之前,我忘了提到我想了解如何在不使用第三方库的情况下做到这一点。

如何使用 Node.js 动态生成 Html 内容?

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

(我不反对第三方库。我更喜欢了解 Node.js在学习它之上的库之前

)。
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/');

创建侦听您想要的任何端口的 Web 服务器,然后让它使用您想要的任何 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