【问题标题】:Requesting file directly with Node JS server returns with nothing直接使用 Node JS 服务器请求文件返回没有任何结果
【发布时间】:2025-12-29 20:15:12
【问题描述】:

所以我试图让一个节点 js 服务器来提供文件。即使我直接在 url (http://localhost:8080/media/file.mp3) 中调用文件,它也不会返回任何数据。当我在 write 语句上 console.log 时,它返回 false,这意味着部分或全部数据没有被刷新并发送到客户端。

代码:

http.createServer(function(req, res){
res.on('end',()<= {
    if (req.url.includes("media")){
        res.setHeader('Content-Type','audio/mp3');
        res.setHeader('Retry-After', '1');
        res.setHeader('method','POST');
        res.setHeader('Connection','keep-alive');
        res.writeHead(200,{'Content-Type':'audio/mp3'});
        console.log("/path_to_file_from_root_to_index"+req.url);
        fs.readFile("/path_to_file_from_root_to_index"+req.url,function(err,data){
            if (err){
                console.log(err);
            } else {
                res.write(data);
                res.end();
            }
        });
}).listen(8080);

req.url='/media/file.mp3' 时浏览器中显示的内容:

【问题讨论】:

    标签: node.js file http request response


    【解决方案1】:
    var fs = require('fs'),
        http = require('http'),
        path = require('path');
    
    http.createServer(function(req, res) {
    
        if (req.url.includes('media')) {
    
            res.writeHead(200, {
                'Content-Type': 'audio/mp3'
            });
            console.log(path.join(__dirname, '/path_to_file_from_root_to_index' + req.url));
            fs.readFile(path.join(__dirname, '/path_to_file_from_root_to_index' + req.url), function(err, data) {
                if (err) {
                    console.log(err);
                } else {
                    res.end(data);
                }
            });
        }
    
    }).listen(8080);
    

    【讨论】: