如何使用 ngrok 从本地 Node.js 服务器公开提供图像?

问题描述 投票:0回答:1

我有一个本地

Node.js
服务器在
localhost:3000

上运行

我想使用 Instagram Graph API 在 Instagram 上发布图像(我已在本地存储)

但是 Instragram Graph API 的

POST
需要一个 公共图像 URL,然后它将用来将该图像发布到相关的 Instagram 帐户上。

POST graph.facebook.com/.../?image_url=https://my/public/server/my-image.img

我显然没有运行这样的公共服务器,因为我在本地测试东西

我的本地 Node.js 服务器有这个路由处理程序:

app.get('/my-image.jpg', ((req, res) => {
   // serve image from local folder
})

但它显然会服务于以下图像:

http://localhost:3000/my-image.jpg

这不好

如果我正确理解

ngrok
的目的,我相信我可以将 ngroksomething 一起使用,如下所示:

import ngrok from 'ngrok'
import { 
  v4 as uuidv4
} from 'uuid'

const secureImageRoute = `${uuidv4()}/my-image.jpg`

app.get(secureImageRoute, ((req, res) => {
  // serve image from local folder
})

const ngrokUrlToMyImage = await ngrok.connect({ addr: secureImageRoute })

我使用

uuidv4()
的原因是除了我的服务器之外没有其他人可以访问此路由。

所以之后我希望可以通过以下方式 POST(从我的本地 Node.js 服务器)到 Instagram Graph API:

graph.facebook.com/.../?image_url=${ngrokUrlToMyImage}

现在我的

ngrok
实现显然是错误的。我无法理解有关我应该如何实现我想要的目标的文档。因此,任何帮助将不胜感激。

如果我完全错了,并且我无法使用

ngrok
来实现此目的,请告诉我。

javascript node.js ngrok
1个回答
0
投票

如果有人感兴趣或想要改进,这是我自己的答案(经过测试):

import ngrok             from 'ngrok'
import { v4 as uuidv4 }  from 'uuid'
import express           from 'express'

const myLocalServer = express()
const port = 3000

const ngrokUrl = await ngrok.connect({ 
  addr: port,
  authtoken: 'auth-token-provided-by-ngrok-with-every-free-account'
})

const secureRelativePath = `/${uuidv4()}/instagram/media`
const secureAbsolutePath = `${ngrokUrl}/${secureRelativePath}`


// this handler is now public & remotely accessible by anyone
// but actually only my local server can access & make use of it
// because of the use of uuidv4()
myLocalServer.get(`${secureRelativePath}/:filename`, (req, res) => {
  const img = getImageFromLocalFolder(req.params.filename)
  res.sendFile(img)
})

// this handler is not accessible remotely via the ngrok server
myLocalServer.get('/something-else', (req, res) => {
  if (req.hostname.includes(ngrokUrl) {
    // don't allow public ngrok access to this route
    return
  }
})

// will use this URL with the Instragram Graph API to upload my photo
const publicImgURL = `${secureAbsolutePath}/cat.jpg`

myLocalServer.listen(port, () => {
  console.log(`My local server running on port ${port}`)
})
© www.soinside.com 2019 - 2024. All rights reserved.