微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在localhost上正常工作时,无法在heroku上加载抓取的数据

如何解决在localhost上正常工作时,无法在heroku上加载抓取的数据

我试图建立一个歌词网站(出于测试目的),对于歌词部分,我从azLyrics中抓取了数据,并试图通过res.render index.hbs将数据存储在我的网站上。在本地主机上运行正常,我可以获取歌词,但是当我在heroku上部署时,抓取部分不起作用。

这是我的代码

app.js

const express = require('express');
const path = require('path');
const hbs = require('hbs');
const bodyParser = require('body-parser');
const lyricsClass = require('./assets/partials/lyricsparser');
const state={};

 
const app=express();

const port = process.env.PORT || 5000;
const dirname= path.join(__dirname,'/assets/views/hbs');
const partialPath=path.join(__dirname,'/assets/partials');


app.set('view engine','hbs')
app.set('views',dirname);
hbs.registerPartials(partialPath);
app.use(bodyParser.urlencoded({extended:true}));

app.use('/',(req,res,next)=>{
    console.log('Hello');
    next();
});

app.use(express.static(path.join(__dirname,'/assets')));

app.get('/',res) => {
   res.render('index')
});

app.use('/search',next)=>{
    console.log('app.send works fine')
    next();
})
app.post('/search',res) => {
    ;(async function(){
    const newText = req.body.data.replace(/ /g,"").toLowerCase();
    const newTextData=newText.split(',')
    state.search=new lyricsClass.hello(newTextData[0],newTextData[1]);
    await state.search.getLyricss();
   res.render('lyrics',{
       lyrics:state.search.lyrics
   })
    })();   
});

和lyricssparser.js

    const axios = require('axios')
class hello{
    constructor(singer,song){
        this.singer=singer;
        this.song=song;
    }
   async getLyricss(){
    try{
        const data=await axios(`https://www.azlyrics.com/lyrics/${this.singer}/${this.song}.html`);
        this.dataElement=data.data;
        this.lyrics=this.dataElement.split('<div>')[1].split('</div>')[0];

    }
    catch(error){
        this.lyrics=error;
    }
   }
}

module.exports.hello=hello;

只是为了简化代码,在lyricsparser.js中,我创建了一个名为hello的类,并通过singer name中创建的对象传递了song nameapp.jsstate.search=new lyricsClass.hello(newTextData[0],newTextData[1]),这里state一个空对象。newTextData实际上存储从我的网站search field获取的数据,并根据azlyrics url结构进行修改(类似于“ https://www.azlyrics.com/lyrics/singernamewithoutspace/songnamewithoutspace.html“)。然后,在创建对象之后,我可以轻松地访问方法getLyricss,该方法实际上是将数据抓取并存储到this.lyrics中,并且可以通过对象lyrics访问state.search 。它可以在localhost上正常运行,但是当上传到heroku时,它会给出一个Error: Request Failed with status code 403

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。