要使用Node.js构建服务器并返回HTML页面,您可以按照以下步骤进行操作:

  1. 在您的项目文件夹中创建一个新的文件夹,例如"server"。
  2. 在"server"文件夹中创建一个新的JavaScript文件,例如"app.js"。
  3. 在"app.js"文件中,导入所需的模块:
const http = require('http');
const fs = require('fs');
  1. 创建一个HTTP服务器并指定请求处理逻辑:
const server = http.createServer((req, res) => {
  if (req.url === '/') {
    // 读取HTML文件内容
    fs.readFile('./index.html', 'utf8', (err, data) => {
      if (err) {
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end('Internal Server Error');
      } else {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(data);
      }
    });
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not Found');
  }
});
  1. 启动服务器并监听指定的端口:
const port = 3000;

server.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
  1. 在项目文件夹中创建一个新的HTML文件,例如"index.html",并将所需的内容添加到该文件中。

现在,您可以通过运行node server/app.js命令来启动服务器,并在浏览器中访问http://localhost:3000来查看返回的HTML页面

使用nodejs技术搭建服务器并返回html页面

原文地址: http://www.cveoy.top/t/topic/iFhK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录