Prisma Nextjs 在表单上提交数据之前获取未定义的会话

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

我正在为 postgres 数据库中的对象创建编辑功能。我也在我的会话中使用 nextauth。当我尝试提交表单数据(例如更新架构中定义的字段)时,出现错误,

client_fetch_error undefined
发布到数据库效果很好。 (顺便说一句,我对整个网络开发还是个新手)

我正在使用下一个版本 12.1.2 和下一个身份验证 4.24.6

抱歉,如果我没有包含一些有用的信息,请询问我是否遗漏了任何内容。

这是包含编辑页面所有代码的路线,

import React, { useState } from "react";
import { GetServerSideProps } from "next";
import ReactMarkdown from "react-markdown";
import Layout from "../../../components/Layout";
import Router from "next/router";
import { PostProps } from "../../../components/Post";
import prisma from '../../../lib/prisma'
import { useSession } from "next-auth/react";

export const getServerSideProps: GetServerSideProps = async ({ params }) => {
  const course = await prisma.course.findUnique({
    where: {
      id: String(params?.id) ,
    },
    include: {
      author: {
        select: { name: true, email: true,},
      },
    },
  });
  return {
    props: course,
  };
};

const Post: React.FC<PostProps> = (props) => {
  const { data: session, status } = useSession();
  if (status === 'loading') {
    return <div>Authenticating ...</div>;
  }
  const userHasValidSession = Boolean(session);
  const postBelongsToUser = session?.user?.email === props.author?.email;
  let title = props.title;
  
  title = `${title}`;
  
  const [desc, setDesc] = useState("");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [number, setPhone] = useState("");
  const [courseid, setCourseid] = useState("");

  const submitData = async (e: React.SyntheticEvent) => {
    console.log("got to submit")
    e.preventDefault();
    try {
      const body = { title, courseid, name, email, number, desc };
      await fetch(`/api/post/${props.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      await Router.push("/");
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <Layout>
      <div>
        <h2>{title}</h2>
        <p>By {props?.author?.name || "Unknown author"}</p>
        <ReactMarkdown children={props.desc} />
        <form onSubmit={submitData}>
          
          <h3>Course ID</h3>
          <input
            autoFocus
            onChange={(e) => setCourseid(e.target.value)}
            placeholder="e.g. Math 301"
            type="text"
            value={courseid}
          />
          
          <h3>Teacher's Name</h3>
          <input
            autoFocus
            onChange={(e) => setName(e.target.value)}
            placeholder="Teacher Name"
            type="text"
            value={name}
          />
          <h3>Email</h3>
          <input
            autoFocus
            onChange={(e) => setEmail(e.target.value)}
            placeholder="Email"
            type="text"
            value={email}
          />
          <h3>Phone</h3>
          <input
            autoFocus
            onChange={(e) => setPhone(e.target.value)}
            placeholder="Number"
            type="text"
            value={number}
          />
       
          <textarea
            cols={50}
            onChange={(e) => setDesc(e.target.value)}
            placeholder="Important Notes"
            rows={8}
            value={desc}
          />
           {userHasValidSession && postBelongsToUser && (
          <button type="submit">Edit</button>
        )}
          <a className="back" href="#" onClick={() => Router.push("/")}>
            or Cancel
          </a>
          
        </form>

      </div>
      
    </Layout>
  );
};

export default Post;

这是我的 api 页面,用于处理编辑和删除 [id].ts

import type { NextApiRequest, NextApiResponse } from 'next'
import { getSession } from 'next-auth/react';
import prisma from '../../../lib/prisma'

export default async function handle(req: NextApiRequest, res: NextApiResponse) {
  const postId = req.query.id;
  const { title, courseid, desc, name, email, number } = req.body;
  const session = await getSession({ req })

  if (req.method === "DELETE") {
    if (session) {
      const post = await prisma.course.delete({
        where: { id: String(postId) },
      });
      res.json(post);
    } else {
      res.status(401).send({ message: 'Unauthorized' })
    }
  } 
  else if (req.method === "PUT") {
    console.log("got to api")
    console.log(postId)
    if (session) {
      console.log("got thru if statement in api")
      const post = await prisma.course.update({
        where: { id: String(postId) },
        data: {
          title: title,
          courseid: courseid,
          desc: desc,
        },
      });
      res.json(post);
    } else {
      res.status(401).send({ message: 'Unauthorized' })
    }
  }
  else {
    throw new Error(
      `The HTTP ${req.method} method is not supported at this route.`
    );
  }
}

这是控制台中记录的内容:

https://next-auth.js.org/errors#client_fetch_error undefined {
  error: {},
  url: 'http://localhost:3000/api/auth/session',
  message: undefined
}
got to api
clv5u15cn0000udk0yd2rt9i1
javascript forms session next.js next-auth
1个回答
0
投票

原来是令人讨厌的 getSession 函数。我只需更改为 getServerSession 就可以了。

© www.soinside.com 2019 - 2024. All rights reserved.