ozudev
ozudev

Reputation: 1

Nextjs API route generation -> NextResponse

I want to print the successful data extraction with console.log on the frontend side, but I cannot find the message part.

export async function GET() {
  try {
    const posts = await prisma.post.findMany()

    return NextResponse.json(posts, {message: 'Data Captured Successfully'}, { status: 200 })
  } catch (error) {
    return NextResponse.json({ message: 'Get All Posts Error', error }, { status: 500 })
  }
}

I don't know how logical it is to use statusText to print the message.

export async function GET() {
  try {
    const posts = await prisma.post.findMany()

    return NextResponse.json(posts, { status: 200, statusText: 'Data Captured Successfully' })
  } catch (error) {
    console.error('GET Error:', error)
    return NextResponse.json(
      { message: 'Get All Posts Error', error },
      { status: 500, statusText: 'Data Not Available' },
    )
  }
}

Upvotes: 0

Views: 87

Answers (1)

ozudev
ozudev

Reputation: 1

I called the api this way

const URL = process.env.NEXTAUTH_URL

async function getPosts() {
  try {
    const res = await fetch(`${URL}/api/posts`, { cache: 'no-store' })

    return res.json()
  } catch (error) {
    console.log('Error loading topics', error)
    throw error
  }
}

Upvotes: 0

Related Questions