在 Express 服务器内部获取 - 未定义获取

fetching inside express server - fetch is not defined

我正在尝试从 facebook 获取长期访问令牌...根据文档,我需要从服务器端获取以确保安全。如果我从客户端获取它工作正常 - 但我应该遵循指南..这就是我正在做的 - 你能告诉我为什么我得到服务器端错误 "Reference error: fetch is not defined"?

首先,我从前端创建了一个路由来请求长期存在的令牌。要获得长期令牌,我需要使用短期令牌,因此我在请求参数中发送短期令牌。变量 userAccessTokenShort 有效且已定义。

const newLongLivedUserAccessToken = await fetch(`/api/autoquotegenerators/longLivedUserToken/${userAccessTokenShort}`, {
            method: 'GET',
            headers: {
                Authorization: `Bearer ${token}`,
                "Content-Type": "application/json; charset=UTF-8",
            },
        })
        const newLongUserTokenRes = await newLongLivedUserAccessToken.json()
        console.log(newLongUserTokenRes)

然后,在我的快速服务器上,我创建了一个路由来处理对 Facebook Graph 的获取请求 API。这是我得到参考错误的地方。

//Get Long Lived User Access Token on Backend /express route
router.get('/longLivedUserToken/:shortLived', (req, res) => {
    try {
        const getLongToken = fetch(`https://graph.facebook.com/v7.0/oauth/access_token?grant_type=fb_exchange_token&client_id=#############&client_secret=################&fb_exchange_token=${req.params.shortLived}`)
        .then(token => res.send(token))

    } catch (error) {
        console.log(error)
    }
})

如果一切顺利,应该将新令牌发送回客户端。

感谢您的帮助!

node.js 中没有内置 fetch() 功能。如果你想要在浏览器中看起来很像 fetch() 的东西,你可以看看 NPM 中的 node-fetch module

或者,有lots of modules you can choose from in node.js. My favorite is got().

仅供参考,用于获取 http 请求的内置接口是 http.request()http.get(),但它们级别较低,需要更多行代码才能完成比上述任何名称更简单的操作模块。