next.js 应用程序错误:一个客户端异常已经发生(查看浏览器控制台获取更多信息)

mwngjboj  于 2023-01-17  发布在  其他
关注(0)|答案(5)|浏览(2330)
  • Nextjs博客应用程序 *

当前看到:Application error: a client-side exception has occurred (see the browser console for more information).我在AWS Amplify控制台上的部署中创建帖子时看到上述错误,DynamoDB无法重定向到提交时创建的帖子,但我可以在提交时本地查看帖子。
任何关于为什么会发生这种情况的迹象都是非常感谢的。

///create-post.js
import { withAuthenticator } from '@aws-amplify/ui-react'
import { useState, useRef } from 'react'
import { API, Storage } from 'aws-amplify'
import { v4 as uuid } from 'uuid'
import { useRouter } from 'next/router'
import SimpleMDE from "react-simplemde-editor"
import "easymde/dist/easymde.min.css"
import { createPost } from '../graphql/mutations'
import MySelect from '../components/Autocomplete'
import { useForm } from "react-hook-form";
import { ErrorMessage } from '@hookform/error-message';
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

const initialState = { title: '', content: '', category: '', countries: '', select: '', date: '', createdAt: new Date().toISOString()}

function CreatePost() {
  const [startDate, setStartDate] = useState(new Date());

  const { register, handleSubmit, formState: { errors } } = useForm();
  const onSubmit = data => console.log(data);

  const [post, setPost, state] = useState(initialState)
  const hiddenFileInput = useRef(null);
  const { title, content, category, countries, select, date,  createdAt } = post

  const router = useRouter()
  function onChange(e) {
    setPost(() => ({ ...post, [e.target.name]: e.target.value }))
  }
  
  console.log('setPost', post.countries ? countries.label : "")
  async function createNewPost() {
    if ( !title || !content || !category || !countries || !select || !date ||  !createdAt ) return
    const id = uuid() 
    post.id = id
    await API.graphql({
      query: createPost,
      variables: { input: post },
      authMode: "AMAZON_COGNITO_USER_POOLS"
    })
    router.push(`/posts/${id}`)
    
  }
  return (
    <form onSubmit={handleSubmit(onSubmit)} autoComplete="false"
      noValidate>
    <div>
      <h1 className="text-3xl font-semibold tracking-wide mt-36">Create New Article</h1>
      <p className="mt-6">Enter Title: </p>
      <input
        aria-invalid={errors.title ? "true" : "false"}
        {...register('title', { required: true })}
        onChange={onChange}
        name="title"
        placeholder="Title"
        value={post.title}
        className="border-b pb-2 text-lg my-4 focus:outline-none w-full font-light text-gray-500 placeholder-gray-500 y-2"
        
      />
      {errors.title && (
        <span role="alert" className="mb-4 mt-4 alert">
          This field is required
        </span>
      )}
      <p>Enter Category: </p>
      <input
        aria-invalid={errors.category ? "true" : "false"}
        {...register('category', { required: true })}
        onChange={onChange}
        name="category"
        placeholder="Author Category"
        value={post.category}
        className="mb-4 mt-4 border-b pb-2 text-lg my-4 focus:outline-none w-full font-light text-gray-500 placeholder-gray-500 y-2"
      />
      {errors.category && (
        <span role="alert" className=" alert">
          This field is required
        </span>
      )}
      <p  className="mb-2 mt-2" >Select Created Date: </p>
      <DatePicker
        aria-invalid={errors.date ? "true" : "false"}
        {...register('date', { required: true })}
        selected={post.date}
        onChange={(date) => setPost({...post, date})}
        name="date"
        placeholder="Created date" autoComplete="true"
        className="visible focus:outline-black outline-black"
        
      />
      {errors.date && (
        <span role="alert" className="mb-12 mt-12 alert">
          This field is required
        </span>
      )}
      <div className="mb-2 mt-2">
      <p>Select Author&apos;s Country:</p>
      <MySelect
        aria-invalid={errors.countries ? "true" : "false"}
          {...register('countries', { required: true })}
          options={options}
          name="countries"
          onChange={onChange => setPost({ ...post, countries: onChange.value })}
          value= {post.countries}
          className="m-6"
          placeholder="Countries Select..."
        />
        </div>
        <div className="ml-6 alert">
      {errors.countries && (
        <span role="alert" className="mb-12 mt-12 alert">
          This field is required
        </span>
      )}
      </div>
      <div className="mb-2 mt-2">
      <p>Select Blog&apos;s Category</p>
      <MySelect
        aria-invalid={errors.select ? "true" : "false"}
          {...register('select', { required: true })}
          options={selectCategoryOptions}
          name="select"
          onChange={onChange => setPost({ ...post, select: onChange.label})}
          value= {post.select}
          className="m-6"
          placeholder="select Select..."
        />
        </div>
        <div className="ml-6 alert">
      {errors.select && (
        <span role="alert" className="mb-12 mt-12 alert">
          This field is required
        </span>
      )}
      </div>
      <div className="mb-2 mt-2">
      </div>
        <p className="mt-8" >Enter Blog Content: </p>
      <SimpleMDE 
          aria-invalid={errors.content ? "true" : "false"}
            {...register('content', { required: true })}
          value={post.content} 
          onChange={value => setPost({ ...post, content: value })} 
          />
      {errors.content && (
        <span role="alert"  className="mb-4 mt-4 alert">
          This field is required
            <br/>
            <p className="alert font-semibold"> 
          Please check all fields are filled in  & wait 3 seconds before refreshing the page
          </p> 
          </span>
      )}
      <input
        onChange={onChange}
        name="createdAt"
        placeholder="Time created"
        value={post.createdAt}
        className="invisible"
        
      />
      <br/>
      
      <button
        type="submit"
        className="mb-4 mt-4 bg-blue-600 text-white font-semibold px-8 py-2 rounded-lg"
        onClick={createNewPost}
      >Save Article</button>
    </div>
    </form>
  )
}
const selectCategoryOptions  = [
  {
    label: "Sport"
  },
  {
    label: "News"
  },
  {
    label: "Weather"
  },
  {
    label: "Other"
  }
];
const options = [
  { label: 'Africa', value: 'Africa' },
  { label: 'USA', value: 'USA' },
  { label: 'Asia', value: 'Asia' },
  { label: 'Europe', value: 'Europe' },
  { label: 'Oceania', value: 'Oceania' },
]

export default withAuthenticator(CreatePost)
//pages/posts/[id].js
import { API, Storage } from 'aws-amplify'
import { useState, useEffect } from 'react'
import { useRouter } from 'next/router'
import ReactMarkdown from 'react-markdown'
import { listPosts, getPost } from '../../graphql/queries'

export default function Post({ post }) {
    const router = useRouter()
    if (router.isFallback) {
        return <div>Loading...</div>
    }
    return (
        <div>
        <h1 className="text-5xl mt-4 font-semibold tracking-wide mt-36 text-center">Title: {post.title}</h1>
        <h4 className="text-3xl mt-4 font-semibold tracking-wide text-center">Category: {post.category}</h4>
        <p className="text-1xl mt-4 font-semibold tracking-wide text-center">Selected Category Name: {post.select }</p>
        <div className="m-8 text-center">
            Content: <ReactMarkdown className='prose text-center' >{post.content}</ReactMarkdown>
        </div>
        <time dateTime={post.createdAt} className="invisible">
                Blog gerenated date created at: {new Date(post.createdAt).toDateString()}</time>
                <br/>
        <time dateTime={post.date} className="text-center">
        User date created at: {new Date(post.date).toDateString()}</time>
        <p className="text-1xl mt-4 font-semibold tracking-wide">Author&apos;s Country: {post.countries }</p>
        <p className="text-sm font-semibold my-4">Author:  {post.username}</p>
        </div>
    )
    }

    export async function getStaticPaths() {
    const postData = await API.graphql({
        query: listPosts
    })
    const paths = postData.data.listPosts.items.map(post => ({ params: { id: post.id }}))
    return {
        paths,
        fallback: true
    }
    }

    export async function getStaticProps ({ params }) {
    const { id } = params
    const postData = await API.graphql({
        query: getPost, variables: { id }
    })
    return {
        props: {
            post: postData.data.getPost
        },
        revalidate: 60
    }
}
lf5gs5x2

lf5gs5x21#

在您的pages/blog/[id].js文件中,您需要添加以下内容

//pages/posts/[id].js
import { API, Storage } from 'aws-amplify'
import { useState, useEffect } from 'react'
import { useRouter } from 'next/router'
import ReactMarkdown from 'react-markdown'
import { listPosts, getPost } from '../../graphql/queries'
import Error404 from '../../components/Error404'

export default function Post({ post }) {
    const router = useRouter()

    //Add this
      if (!router.isFallback && !post?.title) {
          return <Error404 />;
      }

    return (
    //Also add this
        {router.isFallback? (<div>Loading...</div>)
        : (<div>
            <h1 className="text-5xl mt-4 font-semibold tracking-wide mt-36 text-center">Title: {post.title}</h1>
            <h4 className="text-3xl mt-4 font-semibold tracking-wide text-center">Category: {post.category}</h4>
            <p className="text-1xl mt-4 font-semibold tracking-wide text-center">Selected Category Name: {post.select }</p>
            <div className="m-8 text-center">
            Content: <ReactMarkdown className='prose text-center' >{post.content}</ReactMarkdown>
            </div>
            <time dateTime={post.createdAt} className="invisible">
                Blog gerenated date created at: {new Date(post.createdAt).toDateString()}</time>
            <br/>
            <time dateTime={post.date} className="text-center">
                 User date created at: {new Date(post.date).toDateString()} 
            </time>
            <p className="text-1xl mt-4 font-semibold tracking-wide">Author&apos;s Country: {post.countries }</p>
            <p className="text-sm font-semibold my-4">Author:  {post.username}</p>
        </div>)
        }
    )
    }

    export async function getStaticPaths() {
    const postData = await API.graphql({
        query: listPosts
    })
    const paths = postData.data.listPosts.items.map(post => ({ params: { id: post.id }}))
    return {
        paths,
        fallback: true
    }
    }

    export async function getStaticProps ({ params }) {
    const { id } = params
    const postData = await API.graphql({
        query: getPost, variables: { id }
    })
    return {
        props: {
            post: postData.data.getPost
        },
        revalidate: 60
    }
}

我不知道它是否适合你。但是我也遇到过同样的错误。上面的代码配置已经修复了我的错误。

lnlaulya

lnlaulya2#

我试图打开MUI页面,但出现错误,
1.我在一个网络博客上找到了一个临时的解决方案,那就是在一个匿名窗口中打开页面
1.最终的解决方案,而不需要打开隐身窗口是从页面删除cookie点击挂锁出现在浏览器的搜索框,选择cookie选项,然后点击删除按钮,并重新加载页面.

ma8fv8wu

ma8fv8wu3#

请确保您的所有链接在头中包含正确拼写的单词crossorigin如下crossOrigin

ao218c7q

ao218c7q4#

我们有同样的问题,通过在整个应用程序中删除MUI按钮的自动对焦来修复。

doinxwow

doinxwow5#

我通过在文档开头删除不必要的导入来解决这个问题

相关问题