Home > database >  How to use API Route in next js?
How to use API Route in next js?

Time:03-08

I am learning how to design api and at the same time how to use next js api route. i have set my first route api/property/[propertyId] that returns the specific property detail

now i am trying to set a dynamic route for the specific property id in page folder page/property/[propertyId]. My issue is when i am getting directed on the specific page the data is not there as expected. i am receiving response for error message. Can someone point out what i did wrong ,please? thanks

pages>api>property>[propertyId]

export default function propertyHandler ({query : {propertyId} } ,res) {
    var parser = new xml2js.Parser({explicitArray : false});
    const data = fs.readFileSync(path.join(process.cwd(),'listing.xml'))
    parser.parseString(data,function (err, results){
    results = results.client.secondhandListing.property

    const filteredProp = results.filter((property) => property.id === propertyId)
    filteredProp.length > 0 ?  res.status(200).json(filteredProp[0]) : res.status(404).json({message: `Property with id: ${propertyId} not found.` })
     })
    
}

pages>property>[id].js
 
export const getDetails = async() => {
      const res = await fetch(`${baseUrl}/api/property/[property.Id]}`)
      const data = res.json()

      return data
  }

export async function getServerSideProps({params: { id } }) {
    const data = await getDetails(`${baseUrl}/api/property/${id}`)

    return {
        props: {
            propertyDetails: data
        }
    }
}

CodePudding user response:

i got the answer to my mistake from somewhere else. It was my getdetails function that was wrong. i have amended it to

export const getDetails = async(baseUrl)=>{
    const res = await fetch(baseUrl)
    const data  = await res.json()
    return data
    
};

and it worked. Hope this will be helpful for someone :)

  • Related