Damith Tharuka
Damith Tharuka

Reputation: 11

why does my API route in next.js is giving 404 error

why does my fetch request gives me the error "GET http://localhost:3000/api/db/getRideTypes 404 (Not Found)" when trying to fetch data from sanity client.

The partial code of Rideselector.js is

//"use client";

import Image from 'next/image'
import ethLogo from '../assets/eth-logo.png'
import { useEffect, useState } from 'react'

const style = {
    wrapper: `h-full flex flex-col`,
    title: `text-gray-500 text-center text-xs py-2 border-b`,
    carList: `flex flex-col flex-1 overflow-scroll`,
    car: `flex p-3 m-2 items-center border-2 border-white`,
    selectedCar: `border-2 border-black flex p-3 m-2 items-center`,
    carImage: `h-14`,
    carDetails: `ml-2 flex-1`,
    service: `font-medium`,
    time: `text-xs text-blue-500`,
    priceContainer: `flex items-center`,
    price: `mr-[-0.8rem]`,
}

const basePrice = 15530

const RideSelector = () => {
    const [carList, setCarList] = useState([])

    useEffect(() => {
        ;(async () => {
          try {
            const response = await fetch('api/db/getRideTypes')
            
            const data = await response.json()
            setCarList(data.data)
            
          } catch (error) {
            console.error(error)
          }
        })()
    }, [])

The getRideTypes.js is

import { client } from "../../../../../lib/sanity"

const query = `
*[_type=="rides"]{
    "service": title,
    "iconUrl": icon.asset->url,
    priceMultiplier,
    orderById
}|order(orderById asc)
`

const getRideTypes = async (req, res) => {
    try {
      const sanityResponse = await client.fetch(query)
      console.log(sanityResponse)
  
      res.status(200).send({ message: 'success', data: sanityResponse })
    } catch (error) {
      
      res.status(500).send({ message: 'error', data: error.message })
    }
}
export default getRideTypes

The getRideTypes.js is inside the api folder which has the structure of src/app/pages/api/db/getRideTypes.js. src is in the root. RideSelector.js is in the components folder that is in the root directory same as the src folder.

Upvotes: 1

Views: 925

Answers (2)

start building from here,

  1. move api folder out of app, and inside pages
<project root>
     |- src?/pages/api/db/getRideTypes.js
  1. check if OK when accessing directly to localhost:3000/api/db/getRideTypes (in case the port is set to default 3000)
  2. if not, step back to this simple example in <projectroot>/src?/pages/api/hello.js and check that appears directly in browser at localhost:3000/api/hello
import type { NextApiRequest, NextApiResponse } from 'next'
 
type ResponseData = {
  message: string
}
 
export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<ResponseData>
) {
  res.status(200).json({ message: 'Hello World!' })
}

if OK, then insert in the client component the corresponding fetch (consider useEffect when async, mind the mandatory clause "use client" in the client component at the top of the script),

async function fun_fetchtest() {
   const response = await fetch('/api/hello')
   console.log(`resp: ${response.status}`);

and check in the browser console that appears the message of hello world. if ok, then you solved the problem and you can start to build from here your functionality.

Upvotes: 0

Fabio Nettis
Fabio Nettis

Reputation: 2863

The request path is invalid, the correct path would be /api/db/getRideTypes. Also uncomment the "use client"; directive at the top of the ride selectors file because you are using state in that component.

Upvotes: 1

Related Questions