【问题标题】:hide file extension in url in a server code wrote in nodejs在用nodejs编写的服务器代码中隐藏url中的文件扩展名
【发布时间】:2021-02-08 14:59:51
【问题描述】:

请帮帮我,我刚开始学习 noode.js,但我不知道如何在从本地主机访问时隐藏 URL 中的扩展名(我在 node.js 中编写了代码)

        var http = require('http');
        var fs = require('fs');
        const port = 5050
        var url = require('url');

        const server = http.createServer(function (req, res) {
var q = url.parse(req.url, true);
var filename = "." + q.pathname;
console.log(q);
fs.readFile(filename, function(err, data) {
  if (err) {
    res.writeHead(404, {'Content-Type': 'text/html'});
    return res.end("404 Not Found");
  } 
  else if(filename == './getmoved.html') 
  {
    res.writeHead(301, {'Content-Type': 'text/html'});
    res.write(data);
  }
  else
  {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write(data);
  }
  return res.end();
});
   }).listen(5050);

当我在网络浏览器中打开一个 URL 为 http://localhost:5050/index 时,它应该打开 index.html

【问题讨论】:

    标签: html node.js


    【解决方案1】:

    通常,您最好为节点使用网络服务器,例如 Express.js。但出于教育目的,我会尝试以下方法。

    在您的server.js 文件旁边创建一个名为public 的文件夹并添加以下三个文件:

    1. 404.html
    2. index.html
    3. otherpage.html

    404.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>404</title>
    </head>
    <body>
    <p>Oops! Page not found...</p>
    </body>
    </html>
    

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Index page</title>
    </head>
    <body>
    <p>This is the index page</p>
    </body>
    </html>
    

    otherpage.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <p>The other page</p>
    </body>
    </html>
    

    最后是节点网络服务器 server.js:

    const util = require('util');
    const http = require('http');
    const url = require('url');
    const path = require('path');
    const fs = require('fs');
    
    // Promisify some functions so async/await syntax can be used
    const fsReaddir = util.promisify(fs.readdir);
    const fsReadFile = util.promisify(fs.readFile);
    
    const port = 5050
    
    // Define a folder to store the html files
    const publicDir = path.join(__dirname, 'public');
    
    const server = http.createServer(async function (req, res) {
    
      // Read the filenames in your public folder
      const allFiles = await fsReaddir(publicDir);
    
      // Optionally filter out any files with another extension than html
      const htmlFiles = allFiles.filter(fileName => /\.html$/.test(fileName))
    
      // Parse the requested url
      const q = url.parse(req.url, true);
      console.log('Requested: ' + q.pathname);
    
      // If no path is given, default to index.html
      if(q.pathname === '/') {
        console.log('Falling back to index')
        const data = await fsReadFile(path.join(publicDir, 'index.html'));
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(data.toString());
        res.end();
        return;
      }
    
      // Loop through all html files
      for(const htmlFile of htmlFiles) {
        const requestedPath = path.join(publicDir, q.pathname) + '.html';
        const actualPath = path.join(publicDir, htmlFile);
    
        // Check for a matching file
        if(requestedPath === actualPath) {
          console.log('Found match :-)');
          // It did match, so read the data of the file and respond
          const data = await fsReadFile(requestedPath);
          res.writeHead(200, {'Content-Type': 'text/html'});
          res.write(data.toString());
          res.end();
          return;
        }
      }
    
      console.log('Page not found...');
      // No mathces were found, so respond with 404
      const data = await fsReadFile(path.join(publicDir, '404.html'));
      res.writeHead(404, {'Content-Type': 'text/html'});
      res.write(data);
      res.end();
    
    }).listen(port);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-14
      • 2014-08-08
      • 2012-03-06
      • 2019-01-02
      • 2014-03-29
      • 1970-01-01
      相关资源
      最近更新 更多