简体   繁体   English

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

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

I'm trying to generate a url using nodeJS that points to a static resource, which is a JS file. 我正在尝试使用nodeJS生成一个指向静态资源的URL,这是一个JS文件。 It throws me a 404 error, Not Found. 它抛出了404错误,Not Found。

First I start the node server with node index.js 首先,我用node index.js启动节点服务器

The node.js file has this: 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...');

Now, I've got index.js inside var/www/html/avisoPago 现在,我在var / www / html / avisoPago中有index.js

And my avisos-de-pago.html file is inside the avisoPago folder that's inside avisoPago. 我的avisos-de-pago.html文件位于avisoPago内的avisoPago文件夹中。

So the path to index.js is: var/www/html/avisoPago/index.js 所以index.js的路径是: var / www / html / avisoPago / index.js

And the path to avisos-de-pago.html file is: var/www/html/avisoPago/avisoPago/avisos-de-pago.html avisos-de-pago.html文件的路径是: var / www / html / avisoPago / avisoPago / avisos-de-pago.html

What Am I doing wong that it doesn't find the file when I type http://myDomain:3000/avisarPagoAhora 当我输入http:// myDomain:3000 / avisarPagoAhora时,我在做什么,它找不到文件

var path = req.url.toLowerCase(); The "toLowerCase" function makes the "avisarPagoAhora" turn into "avisarpagoahora" and because of it node can't find the right path '/avisarPagoAhora' . “toLowerCase”功能使“avisarPagoAhora”变成“avisarpagoahora”,因为它节点找不到正确的路径'/avisarPagoAhora' Try to remove the toLowerCase function or make the case statement " case '/avisarpagoahora': " 尝试删除toLowerCase函数或使case语句“ case '/avisarpagoahora':

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM