簡體   English   中英

使用 next.js 構建的實時網站上的客戶端獲取錯誤

[英]client fetch error on live website built using next.js

嗨,我已經嘗試了所有可能的方法來找出在使用 NEXTJS 構建的實時網站上可能導致上述錯誤的原因。

我注意到每當我重新加載網站時都會發生此錯誤。

我還注意到,每當我嘗試使用用戶名和密碼登錄時,我都可以在本地主機中沒有任何錯誤,並且還可以使用https://codesandbox.io 但是在實時站點上,我收到服務器錯誤“服務器配置問題。”。

當我在開發人員工具上進一步滾動時,我會發現以下附加信息。

Unexpected token < in JSON at position 0 {error: {…}, path: "session", message: "Unexpected token < in JSON at position 0"

我在vercel中添加了以下環境變量

NEXTAUTH_URL = https://****.vercel.app/
MONGODB_URI = mongodb+srv://****@cluster0.9kc5p.mongodb.net/*****?retryWrites=true&w=majority

我的 [...nextauth].js 文件如下

import NextAuth from "next-auth";
import CredentialsProviders from "next-auth/providers/credentials";
import { verifyPassword } from "../../../lib/hashedPassword";

import clientPromise from "../../../lib/mongodb";

export default NextAuth({
  session: {
    strategy: "jwt"
  } /* check other providers you may add database etc */,
  providers: [
    CredentialsProviders({
      /* authorize will be called when it receives incoming login req */
      async authorize(credentials) {
        const client = await clientPromise;
        const db = client.db();
        /* check if we have user or email */
        const usersCollection = await db.collection("users");

        const user = await usersCollection.findOne({
          $or: [
            { email: credentials.email },
            { userName: credentials.userName }
          ]
        });

        if (!user) {
          throw new Error("No user found");
        }
        const isvalid = await verifyPassword(
          credentials.password,
          user.password
        );

        if (!isvalid) {
          throw new Error("password is invalid");
        }

        return {
          email: user.email
        }; 
      }
    })
  ]
});

我的登錄頁面如下

import Button from "../../UI/Button/Button";
import Input from "../../UI/Input/Input";
import Card from "../../UI/card/Card";
import classes from "./Login.module.css";
import Link from "next/link";
import { useForm } from "react-hook-form";
import { signIn, getSession } from "next-auth/react";
import { useRouter } from "next/router";

const Login = () => {
  const route = useRouter();
  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm();

  const submittedFormHandler = async (userInputs) => {
    const result = await signIn("credentials", {
      redirect: false,
      email: userInputs.userNameEmail,
      userName: userInputs.userNameEmail,
      password: userInputs.password
    }); /* result will always resolve */
    if (!result.error) {
      route.replace("/");
    }
  };

  return (
    <>          

      <Card className={classes.login}>
        <form onSubmit={handleSubmit(submittedFormHandler)}>
          
          <Input
            htmlFor="userNameEmail"
            id="userNameEmail"
            label="UserName or Email"
            input={{
              type: "text",
              ...register("userNameEmail", { required: true})
            }}
          ></Input>
          <span className={classes.spanning}>
            {errors.userName &&
              "Enter userName or Email at least four characters"}
          </span>

          <Input
            htmlFor="password"
            id="password"
            label="Enter Password"
            input={{
              type: "password",
              ...register("password", { required: true, minLength: 8 })
            }} 
          ></Input>
          <span className={classes.spanning}>
            {errors.password && "password should be at least 8 characters"}
          </span>
          <div className={classes.password}>
            <Button type="submit">Submit</Button>
            <Link href="/ForgotPassword">Forgot Password ?</Link>
          </div>
          <Link href="/NewUser" className={classes.link}>
            Create Account New User
          </Link>
        </form>
      </Card>
    </>
  );
};


export async function getServerSideProps(context) {
  const session = await getSession({
    req: context.req
  }); //returns session obj or null
  if (session) {
    return {
      redirect: {
        destination: "/",
        permanent: false
      }
    };
  }
  return {
    props: { session }
  };
}

export default Login;

可能是什么問題呢? 請協助

我遇到了同樣的問題,但是我使用mysql作為數據庫,並且我沒有使用建議 next- auth的身份驗證文件中間件來處理提供程序,而是創建了一個單獨的文件來處理續集(在您的情況下將是 orm與您正在使用的數據庫)。

我修復了它,將dialectModule添加到 class Sequelize的屬性中

const db = new Sequelize(`${process.env.DB_URI}`, {
  database: process.env.DB_NAME,
  logging: false,
  dialect: "mssql",
  dialectModule: require("mysql2"),
});

我也有這個問題。 他們在文檔上說確保您正確定義NEXTAUTH_URL變量。 如果使用 Vercel 托管,那么變量的內容應該只有 url 沒有引號。 例如, https:project.vercel.app

如果沒有解決,請嘗試將[...nextauth].ts文件更改為更簡單的版本。 當我嘗試在回調中使用數據庫(在我的情況下為 mongodb)時,我得到了這個錯誤

 async jwt({ token }) {
    let role:Role = 'user'
    if (!token.email) throw Error('no email provided with token')
    let user = await getUser(token.email)
    if (user?.isAdmin) role = 'admin'
    return {...token, role}
 }

刪除后,我的問題就解決了。 在您的情況下,您可以嘗試刪除與數據庫打交道的任何內容。

在我開始工作后,我添加了這個回調 function

 async jwt({ token }) {
    let role:Role = 'user'
    if (!token.email) throw Error('no email provided with token')
    const client = await clientPromise
    const collection = client.db().collection('users')
    const user = await collection.findOne({email:token.email})
    if (user?.isAdmin) role = 'admin'
    return {...token, role}
}

唯一的區別是第一個使用 mongoose,第二個沒有。 第二種方法取自https://github.com/vercel/next.js/tree/canary/examples/with-mongodb

免責聲明:我不知道它為什么起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM