【问题标题】:How to make my server fetch js file instead of fetching html again?如何让我的服务器获取 js 文件而不是再次获取 html?
【发布时间】:2023-04-08 06:05:02
【问题描述】:

我有一个使用 bundle.js 文件的 index.html。它在本地机器上运行良好。但是当尝试对服务器做同样的事情时,它只显示 html 文件内容。当查看控制台中的代码而不是常规的 js 代码时,bundle.js 文件包含相同的 html 代码。这是我使用的服务器代码。

var http = require('http');
var fs = require('fs');
const PORT=3012; 

fs.readFile('./index.html', function (err, html) {

    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(PORT);
});

【问题讨论】:

    标签: javascript html node.js server


    【解决方案1】:

    为了在不使用 express 或其他已经过测试和首选方式的情况下提供您的 bundle.js 文件和其他文件,您可以提供您喜欢的任何文件(请参阅“routeToFile”函数)。

    //Return the file path you want to serve to that request url
    const routeToFile = ({url}) => {
        if(url === '/'){
            return './index.html';
        }
    
        return `.${url}`;
    }
    

    使用“mimeTypes”数组,您只需检查文件扩展名 (mimeTypes[fileExtension]) 即可猜出正确的 mime 类型。

    //File mime types for content type response
    const mimeTypes = {
        '.html': 'text/html',
        '.js': 'text/javascript',
        '.css': 'text/css',
        '.json': 'application/json',
        '.png': 'image/png',
        '.jpg': 'image/jpg'
    };
    
    

    如果出现错误,例如文件不存在,只需发送错误代码,或者您也喜欢的页面(参见“onError”函数)

    //If the file is missing or there is an error
    const onError = (error, response) => {
        if(error.code == 'ENOENT') {
            response.writeHead(404);
        }
        else {
            response.writeHead(500);
            console.error(error);
        }
    
        response.end();
    }
    

    最后,运行所有这些的主要函数是:

    //Create the http server
    http.createServer((req, res) => {
    
        const filePath = routeToFile(req)
        const fileExtension = String(path.extname(filePath)).toLowerCase();
        const contentType = mimeTypes[fileExtension] || 'application/octet-stream';
    
        fs.readFile(filePath, function(error, content) {
            if (error) {
                return onError(error, res)
            }
            else {
                res.writeHead(200, { 'Content-Type': contentType });
                res.end(content, 'utf-8');
            }
        });
    
    }).listen(PORT, () =>{
        console.log(`server start at port ${PORT}`);
    });
    

    不要忘记要求,否则它将无法运行:D

    const http = require('http');
    const fs = require('fs');
    const path = require('path');
    const PORT = 3012
    

    【讨论】:

    • 如果您有任何问题我想帮助您,但您必须更详细地描述问题。
    猜你喜欢
    • 2021-06-03
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    • 2014-05-12
    • 2021-03-18
    • 2020-12-01
    相关资源
    最近更新 更多