nodeJS:使用(fs)尝试访问静态资源,但收到404错误

nodeJS: using (fs) to try and access a static resource but receive 404 error?

本文关键字:资源 错误 静态 访问 使用 fs nodeJS      更新时间:2023-09-26

我正试图使用指向静态资源的nodeJS生成一个url,该资源是一个JS文件。它给我一个404错误,找不到。

首先,我用node index.js 启动节点服务器

node.js文件包含以下内容:

var fs = require('fs');
function serveStaticFile(res, path, contentType, responseCode) {
    if(!responseCode) responseCode = 200;
    fs.readFile(__dirname + path, function(err,data){
        if(err){
            res.writeHead(500,{'Content-Type': 'text/plain'});
            res.end('500 - Internal Error');
        } else {
            res.writeHead(responseCode,
                    {'Content-Type': 'text/plain'});
            res.end(data);
        }
    });
}
http.createServer(function(req,res){
    var path = req.url.toLowerCase();
    switch(path) {
        case '/avisarPagoAhora':
                serveStaticFile(res, '/avisoPago/avisos-de-pago.html', 'text/html');
                break;
        default:
                res.writeHead(404,{'Content-Type': 'text/plain'});
                res.end('Not Found');
                break;      
    }

}).listen(3000);
console.log('Server started on localhost:3000; press Ctrl-C to terminate...');

现在,我在var/www/html/avisoPago 中有了index.js

我的avisos-dep-pago.html文件在avisoPago文件夹中。

因此,index.js的路径是:var/www/html/avisoPago/index.js

avisos-de-pago.html文件的路径为:var/www/html/avisoPago/aviso-de-pago.html

我在做什么,当我键入时它找不到文件http://myDomain:3000/avisarPagoAhora

var path = req.url.toLowerCase();"toLowerCase"函数使"avisarPagoAhora"变成"avisarpagahora",因此节点无法找到正确的路径'/avisarPagoAhora'。尝试删除toLowerCase函数或使case语句"case '/avisarpagoahora':"