如何使我的服务器获取js文件而不是再次获取html?

时间:2019-06-12 12:04:30

标签: javascript html node.js server

我有一个使用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);
});

1 个答案:

答案 0 :(得分:0)

为了在不使用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