GET http://localhost:3000/api/products/sofa-happy-2-cho-va-2-armchair-vai 404 (Not Found) AxiosError

46 Views Asked by At

when I click a Product, I want to show product details. However, when I clicked a product, It appeared the error: GET http://localhost:3000/api/products/sofa-happy-2-cho-va-2-armchair-vai 404 (Not Found) AxiosError When I saw this error, I thought I made api end point wrong, then I checked again and my api end point was right. Then I thought maybe the slug I wanted to get wrong, I console.log slug and it didnt wrong. I also checked the function in getProductDetail and it's normal. Please help me, I dont know where I was wrong. This is my code

I made an api route like this api/products/[slug]/route.js and code inside like this:

import { connect } from '@/backend/config/mongodb'
import { NextResponse, NextRequest } from "next/server"
import Product from '@/backend/models/Product'

connect()

export async function GET(req) {
    try {
        const product = await Product.find({ slug: req.query.slug })
        if (!product) {
            return NextResponse.json(
                { error: "Product not found!" },
                { status: 404 }
            )
        }
        return NextResponse.json({
            success: true,
            product
        })
    } catch (error) {
        return NextResponse.json({ error: error.message }, { status: 500 })
    }
}

Then I made a ProductDetails page like this (routes)/products/[slug]/page.jsx

'use client'
import React, { useState, useEffect } from 'react'
import ProductDetail from '../../../components/product/ProductDetail'
import axios from 'axios'

export default function Product({ params }) {
    const [product, setProduct] = useState([])
    useEffect(() => {
        const getProductDetails = async () => {
            try {
                const { data } = await axios.get(`${process.env.NEXT_PUBLIC_API_URL}/api/products/${params.slug}`)
                setProduct(data.product)
            } catch (error) {
                console.log(error)
            }
        }

        getProductDetails()
    }, [params.slug])

    return (
        <div>
            <ProductDetail product={product} />
        </div>
    )
}

In ProductDetail page I console.log the product props and it return an empty array

Please help me find the error. I'm using NEXTJS

I want to fix this error

0

There are 0 best solutions below