1

我正在尝试使用 Vercel 而不是 Netlify部署此存储库: https ://github.com/DataStax-Examples/astra-tik-tok。

我将原版 React 重构为 Next.js,但在Home.js文件中我不明白如何将其迁移到 Vercel 的等价物:

//fetch all the tik-tok posts to your feed
const fetchData = async () => {
    const results = await axios.get('/.netlify/functions/posts')
    console.log(results.data)
    setUsers(results.data)
}

有任何想法吗?

4

1 回答 1

0

Next.js 中的等价物是API 路由,它们在 Vercel 中部署为无服务器函数。它们必须在/pages/api文件夹下创建。

您需要稍微重构函数以使用 Next.js。例如,add.js作为 API 路由,您的函数将如下所示。

// /pages/api/add.js
export default function handler(req, res) {
    const users = await getCollection();
    try {
        const user = await users.create(id, event.body);
        res.status(200).json(user);
    } catch (e) {
        console.error(e);
        res.status(500).json({ error: JSON.stringify(e) })
    }
};

然后,您可以通过指向/api/add.

await axios.get('/api/add')
于 2022-01-16T00:57:27.323 回答