简体   繁体   中英

How to use API Route in next js?

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
        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM