【问题标题】:nodeJS: using (fs) to try and access a static resource but receive 404 error?nodeJS:使用(fs)尝试访问静态资源但收到 404 错误?
【发布时间】:2016-09-04 18:49:54
【问题描述】:

我正在尝试使用 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

我的aviso-de-pago.html 文件位于avisoPago 中的avisoPago 文件夹中。

所以 index.js 的路径是:var/www/html/avisoPago/index.js

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

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

【问题讨论】:

  • 发送console.log(__dirname + path) 以查看它实际要查找的文件。

标签: javascript node.js path fs


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-03-30
    • 2017-04-07
    • 2019-06-28
    • 2012-11-30
    • 2012-10-17
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    相关资源
    最近更新 更多