首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >部署在Heroku上的应用程序,但是api调用现在失败了(加载资源失败: net::ERR_CONNECTION_REFUSED,TypeError:未能获取)

部署在Heroku上的应用程序,但是api调用现在失败了(加载资源失败: net::ERR_CONNECTION_REFUSED,TypeError:未能获取)
EN

Stack Overflow用户
提问于 2022-08-04 22:39:26
回答 1查看 83关注 0票数 0

我的应用程序成功地部署在Heroku上--当我让VSCode打开并手动执行npm运行启动时,它可以工作,但是当我关闭VSCode时,它就不能成功地调用后端的任何API了,控制台显示了一些类似标题中的错误。

我的控制台(只在关闭VSCode时发生):

我在后端的代码:

代码语言:javascript
复制
const PORT = 8000
const express = require('express')
const cors = require('cors')
const {TwitterApi} = require('twitter-api-v2')
const axios = require('axios')
const cheerio = require('cheerio')
require('dotenv').config()
const snoowrap = require('snoowrap')
const linkPreviewGenerator = require('link-preview-generator')
const spotify = require('spotify-web-api-node')
const fetch = require('node-fetch')
var request = require('request')

const app = express()
app.use(cors())


app.get('/', async (req, res) => {

    const client = new TwitterApi(process.env.twt_bearer_token)

    const trendsInternational = await client.v1.trendsByPlace(1);

    const trendList = []

    for (const {trends} of trendsInternational) {
        for (const trend of trends) {
            trendList.push({
                name: trend.name,
                url: trend.url
            })
        }
    }

    res.json(trendList)
})



app.get('/reddit', async (req, res) => {
    const r = new snoowrap({
        userAgent: process.env.user_agent,
        clientId: process.env.client_id,
        clientSecret: process.env.client_secret,
        refreshToken: process.env.refresh_token
    })

    topPosts = []
    
    ;(await r.getHot()).forEach(post => {
        topPosts.push({
            title: post.title,
            url: post.url
        })
    })
    
    res.json(topPosts);

})

app.get('/news', async (req, res) => {
    const news_url = 'https://www.theguardian.com/international'

    axios(news_url)
    .then(response => {
        const html = response.data;
        const $ = cheerio.load(html);
        const articles = [];
        const values = new Set();

        $('.fc-item__title', html).each(function () { //<-- cannot be a function expression

            const title = $(this).text().trim();
            const url = $(this).find('a').attr('href');

            if (!values.has(url)) {

              values.add(url);

              articles.push({
                  title,
                  url
              });
            }  
        })
        res.json(articles)
    }).catch(err => console.log(err))


})

app.listen(PORT, () => console.log(`Server is running on port ${PORT}`))```
EN

回答 1

Stack Overflow用户

发布于 2022-08-05 01:14:11

Heroku运行在它自己的端口上,尝试像这样设置端口

代码语言:javascript
复制
const PORT = Number(process.env["PORT"]) || 8000
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73242896

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档