Next JS 和 Vercel——开发与生产

Next JS and Vercel - development vs production

我已经在 Next JS 中构建了一个基本的电影数据库应用程序,以了解该框架的工作原理。这是一个应用程序,允许您使用 NextJS API 端点对 firebase 执行 CRUD 操作。

我的应用程序在开发中运行良好,但它对 Vercel 一次就完全不起作用。我想知道是否有人可以解释一下?

这是初始化时的第一个 'get all data' 调用。其他 API 调用遵循相同的模式。 None 部署后工作。

我的索引页面有这个 getInitialProps 函数…

Home.getInitialProps = async () => {
    const categories = await getCategories()
    const movies = await getMovies()
    const images = movies.map(movie => {
      return {
        id: `image-${movie.id}`,
        url: movie.cover,
        name: movie.name
      }
    })
    
    return {
      movies,
      images,
      categories
    }
  }

这会在此处触发 getMovies 函数……

export const getMovies = async () => {
    const res = await axios.get('http://localhost:3000/api/movies')
    return res.data

它命中的 API 端点看起来像这样……

import firebase from '../../lib/firebase';

export default async(req, res) => {
    const moviesRef = firebase
            .collection('movies');
            const snapshot = await moviesRef.get();
            const movies = [];
            snapshot.forEach(doc => {
                movies.push({ id: doc.id, ...doc.data() })
            })
            res.json(movies)

提前致谢!

您不应在请求的 URL 中硬编码 http://localhost:3000。你应该完全省略它,因为你正在使用 Next.js API 路由(同源)。

export const getMovies = async () => {
    const res = await axios.get('/api/movies')
    return res.data
}

编辑: 如果请求仅发生在 客户端 上,上述解决方案将适用于 API 路由.

由于请求是在 getInitialProps 中发出的,您应该简单地将 API 路由中的逻辑移动到一个单独的函数(在这种情况下很可能是 getMovies)并且而是直接在 getInitialProps 中调用它。

export const getMovies = async () => {
    const moviesRef = firebase.collection('movies');
    const snapshot = await moviesRef.get();
    const movies = [];
    snapshot.forEach(doc => {
        movies.push({ id: doc.id, ...doc.data() })
    });
    return movies;
}

您应该使用您的服务器 link,而不是本地主机。