【问题标题】:Make an API call on the front end using next.js使用 next.js 在前端进行 API 调用
【发布时间】:2022-02-13 17:00:26
【问题描述】:

next.js 的新手,并试图连接从我的组件进行 Prisma 调用。 按照文档和示例执行此操作:

try {
  await fetch('/api/postQuestion', {
    method: 'POST',
    headers: {"Content-Type": "application/json"}
  });
} catch (error) {
  console.error(error);
}

然而,它什么也没做。

这里是 postQuestion.js:

import prisma from "../../lib/prisma.js";

export default async function handler(req, res) {
    if (req.method === 'POST') {
        return await createQuestion(req, res);
    }
    else {
        return res.status(405).json({ message: 'Method not allowed', success: false });
    }
}

async function createQuestion(req, res) {
    try {
        const newQuestion = await prisma.question.create({
            data: {
                question: 'wow?',
                option1: 'blue',
                option2: 'red'
            }
        });
        return res.status(200).json(newQuestion, {success: true});
    } catch (error) {
        console.error("Request error", error);
        res.status(500).json({ error: "Error creating question", success:false });
    }
}

【问题讨论】:

  • “它什么都不做” - 你能澄清一下你的意思吗?你期望你的请求做什么?您没有处理从请求中获得的响应。

标签: reactjs next.js prisma


【解决方案1】:

获取本地 API 数据的正确方法是使用 getStaticProps 函数并返回数据

https://nextjs.org/docs/basic-features/data-fetching/get-static-props

export async function getStaticProps() {
  // Call an external API endpoint to get posts.
  // You can use any data fetching library
  const res = await fetch('https://.../posts')
  const posts = await res.json()

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  }
}

【讨论】:

  • 这将用于非静态内容,例如用户通过 POST 创建内容。所以我不会使用 getStaticProps 对吗?
猜你喜欢
  • 2017-01-04
  • 2021-04-28
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 2017-02-20
  • 1970-01-01
  • 2017-11-26
  • 1970-01-01
相关资源
最近更新 更多