这是我的路由器模块:
router.post("/", function (req, res, next) {
var url = req.body.url;
youtubedl.getInfo(url, function (err, info) {
// handle errors here
if (err) {
console.log(err);
res.status(500).send("youtube-dl error");
} else {
var fields = info.title.split('-');
var artist = sanitizeArtistOrTitle(fields[0].trim());
// TODO: handle possibility of - in artist/song name
var title = sanitizeArtistOrTitle(fields[1].trim());
const options = {
apiKey: geniusKey,
title: title,
artist: artist,
optimizeQuery: true
};
geniusSong(options)
.then(function (result) {
urlFields = result.url.split('/');
// check if the name of the song and artist are in the url
// since the api seems to return a random lyric page
// when the actual page cannot be found
var titleAndArtist = urlFields[3].split('-').join(' ').toLowerCase();
if (titleAndArtist.includes(artist.toLowerCase()) &&
titleAndArtist.includes(title.toLowerCase())) {
// get the lyrics and write to a file
req.options = options;
next();
} else {
res.status(500).send("genius API error on retrieving lyrics");
}
}).catch(function (err) {
console.log(err);
res.status(500).send("genius API unknown error");
})
}
})
}, function (req, res) {
console.log(__dirname);
geniusLyrics(req.options)
.then(lyrics => sanitizeLyrics(lyrics))
.then(sanitizedLyrics => fsPromise.writeFile("./aux_files/words.txt",
sanitizedLyrics.toString()))
.then(console.log("written to file"))
.then(res.status(200).sendFile(path.join(__dirname, "../aux_files", "words.txt"),
{headers: {'Content-Type': 'text/plain'}}))
.catch(function (err) {
console.log(err);
res.status(500).send("Could not write lyrics to file");
});
})
function sanitizeLyrics(lyrics) {
var regexp = /\[[\w ]*\]/g;
return lyrics.replace(regexp, '');
}
// remove unncessary parts of the video title e.g. "feat. ...",
// "[Official Music Video]"
function sanitizeArtistOrTitle(value) {
var regexp = /(ft\..*$|\(.*$|\[.*$|feat\..*$)/
return value.replace(regexp, '');
}
module.exports = router
在app.js中,我有:
var lyrics = require('./routes/lyrics');
app.use('/api/lyrics', lyrics);
我不明白的是,当我的前端调用该路由时,该路由返回了404:
POST /api/lyrics 404 4400.863 ms - 351
我可以在文件系统中看到文件已被写入,因此我知道中间件已成功执行,但是我不确定错误是从哪里来的。如果我尝试再次从路由获取(在创建文件之后),则没有错误,并且一切正常。