Nodejs API 在本地主机中回复 JSON,但相同的 API 调用,在部署 heroku 时回复空的 JSON

问题描述

app.js

const app = express()
const port = process.env.PORT || 5000

var cors = require('cors')


var bodyparser= require('body-parser')

app.use(bodyparser.json());

const route=require('./routes')

app.use(cors());

app.use('/api',route)


app.listen(port,() => {
  console.log(`Example app listening at http://localhost:${port}`)
})


routes.js

const express=require('express');
const Instagram = require('instagram-downloader');

const router=express.Router();

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

    res.json("App Running...")

})


  
  
router.get("/inst",async (req,res)=>{
  
  
  ps=req.query.ps
    
    try {
      
    await Instagram(ps)
    .then(data => {
      const { entry_data: { PostPage } } = data;
      return PostPage.map(post => post.graphql.shortcode_media)
    })
    .then(images => images.map(img => res.json(img.video_url)))
    .then(console.log)
  
    } catch (error) {
      res.json(error)
    }
  
  })
  
  
  
  
module.exports=router;

package.json

{
  "name": "final","version": "1.0.0","description": "","main": "index.js","scripts": {
    "test": "echo \"Error: no test specified\" && exit 1","start": "node apps.js"
  },"keywords": [],"author": "","license": "ISC","dependencies": {
    "body-parser": "^1.19.0","cors": "^2.8.5","express": "^4.17.1","instagram-downloader": "0.0.0"
  }
}

localhost result

当我运行 API 调用 http://localhost:5000/api/inst?ps=https://www.instagram.com/p/BaaDHe5AdPH/?utm_source=ig_web_copy_link 它返回一个 JSON。

heroku result

当我在 heroku 上运行相同的 API 调用 (https://reels2.herokuapp.com/api/inst?ps=https://www.instagram.com/p/BaaDHe5AdPH/?utm_source=ig_web_copy_link) 时,它什么都不返回。

请帮我解决这个问题

解决方法

这很可能是由于发出请求的 IP 地址所致。 Instagram 不允许此类 API 请求。它在您的本地主机上运行,​​因为 Instagram 可以检测到此 IP 属于真实人而非虚拟服务器。

可以通过在使用用户名和密码进行身份验证后创建会话然后使用此会话发出 API 请求来解决。另请注意,通过服务器登录也会导致问题,因为 IP 地址不会被识别并被视为可疑帐户活动。您将被要求通过登录挑战。

,

通过正确处理错误,您将看到实际的错误。

遗憾的是,错误对象默认序列化为 {} 我觉得 nodejs 的创建者在这里做了一个错误的选择。 尽管如此:

var error = new Error('hello');
res.json(error)
// returns an empty object

因为

var error = new Error('hello');
console.log(JSON.stringify(error));
// shows {}
console.log(error);
// shows actual error
console.log(JSON.stringify({message: error.message,stack: error.stack}));
// "correctly" convert error to json

序列化错误对象的另一种方法是使用这个包:https://www.npmjs.com/package/serialize-error

并详细说明情况:Is it not possible to stringify an Error using JSON.stringify?

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...