2016-10-17 7 views
3

사용자가 업로드 한 모든 노래가 업로드되는 디렉토리가 있습니다. 나는이 응용 프로그램을 위해 mongodb를 사용했지만 mongodb는 잘 작동하지만 사용하고 싶다 src url은 노래/사용자/노래 이름에 업로드/무언가를 좋아한다. Controller.js에 표시된대로 Router.get을 사용하려고 시도했다. 그러나 내가 사용할 때 이건 내가 내부 500 오류가있어, 내가 실수로 knwo 알려 주시기 바랍니다.정적 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으로는 브라우저에서 열린이 코드를 사용해보십시오 사전 :

+0

은 어쩌면 귀하의 경우에 도움이되는 HTML 기본 태그를 사용하여, 서버/특급 설정/구문 오류가 아니라면 : http://www.w3schools.com/tags/tag_base.asp – mika

+0

왜하지 와이 o 생성 된 HTML 파일 (브라우저가 보는 것)이 아닌 템플릿을 보여줍니다. 브라우저에서보기/소스를 사용하여이를 얻을 수 있습니다. 아마 HTML 페이지에서 노래 URL이 잘못되었지만 HTML을 생성해야 볼 수 있습니다. – jfriend00

답변

2

디렉토리를 업로드/songName으로

고맙다을 사용합니다 : 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 편집을했는데 이제는 charm \ m / –