2016-10-17 100 views
3

我有一个目录,其中用户上传的所有歌曲都会上传。我已经使用mongodb这个应用程序,mongodb工作正常,但我想用 src url like uploads/something to songs/user/songname我尝试使用Router.get,如Controller.js中所示 但是当我使用这是我得到的内部500错误,请让我知道我犯了什么错误。将静态URL更改为动态 - NodeJS

controller.js

Router.get('/songs/:artist/:song', (req, response) => { 
    console.dir(req.query) 
    let file = './uploads/01-Whole Lotta Love.mp3' 
    var stat = FileSystem.statSync(file) 

    response.setHeader('Content-Type', 'audio/mpeg'); 
    response.setHeader('Content-Length', stat.length); 

    fs.createReadStream(file).pipe(response); 
}) 

app.js

app.use(Express.static(path.join(__dirname, 'uploads'))); 

profile.ejs

<table border="1"> 
    <% artist.songs.forEach((song) => { %> 
    <tr> 
     <td> <%= song.song %> </td> 
     <td> 
      <audio controls> 
       <source src="./songs/<%= artist.artistName+ '/' + song.audioPath %>" type="audio/mpeg"> 
       Your browser does not support the audio element. 
      </audio> 
     </td> 
     <td>3k listens</td> 
     <td>2k likes</td> 
     <td>2k comments</td> 
    </tr> 
    <% }) %> 
</table> 

它像什么都我写的歌/anyusername/SONGNAME将使用目录上传/ SONGNAME

三江源提前:)

+0

除非它是一个服务器/快递配置/语法错误,也许使用HTML基标记你的情况可能会有所帮助:http://www.w3schools.com/tags/tag_base.asp – mika

+0

为什么不ÿ ou显示生成的HTML文件的外观(浏览器看到的内容),而不是模板。你可以在浏览器中使用View/Source来获得。在HTML页面中,您的歌曲网址可能是错误的,但您需要查看生成的HTML以确认。 – jfriend00

回答

2

试试这个代码,在浏览器中打开:http://host:port/song/foo/bar
和评论写什么你得到:

const 
    fs = require('fs'), 
    path = require('path'), 
    bufferSize = 100 * 1024; 

Router.get('/songs/:artist/:song', (req, res) => { 
    let 
    file = '01-Whole Lotta Love.mp3'; 
    file = path.join(__dirname, 'uploads', file); 

    console.log('Piping file:', file); // check if path is correct 

    fs.stat(file, 
    (err, stat) => { 
     if(err) { 
     return res.status(500).send(err); // output error to client 
     } 

     res.writeHead(200, { 
     'Cache-Control': 'no-cache, no-store, must-revalidate', 
     'Pragma': 'no-cache', 
     'Expires': 0, 
     'Content-Type': 'audio/mpeg', 
     'Content-Length': stat.size 
     }); 
     fs.createReadStream(file, {bufferSize}).pipe(res); 
    }); 
}) 
+1

非常感谢@ num8er我对你的代码做了一些url编辑,现在它开始作为魅力工作\ m / –