Экспресс возвращает 404, даже если маршрут существует

#node.js #express

#node.js #экспресс

Вопрос:

Это мой модуль маршрутизатора:

 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()) amp;amp;
                        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

Я вижу в своей файловой системе, что файл был записан, поэтому я знаю, что промежуточное программное обеспечение выполнено успешно, но я не уверен, откуда исходит ошибка. Если я снова попытаюсь выполнить выборку с маршрута (после создания файла), ошибки не будет, и все работает правильно.

Комментарии:

1. если я правильно понял, вы отправляете сообщение в «/», то есть правильный ли этот путь router.post(«/», function (req, res, next)?

2. Из описания, которое OP отправляет в POST /api/lyrics

3. Я смог взломать временное решение, добавив setTimeout перед отправкой ответа OK, но я не уверен, почему это работает.