I'm receiving a 404 error on my API route in next.js - what could be causing this

What could be causing the error message "GET http://localhost:3000/api/db/getRideTypes 404 (Not Found)" when attempting to fetch data from the sanity client?

Here is a snippet of code from Rideselector.js:

//"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 file contains the following code:

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 file is located in the api folder at src/app/pages/api/db/getRideTypes.js. The RideSelector.js is within the components folder which is also at the root directory along with the src folder.

Answer №1

There appears to be an issue with the requested path - the accurate path should read as /api/db/getRideTypes. Additionally, remember to remove the comments surrounding the "use client"; directive at the beginning of the ride selectors file due to state being utilized in that particular component.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking to combine cells within a table using the Exceljs library

Encountered an issue while generating a worksheet in the EXCELJS library. function save_export(){ var workbook = new ExcelJS.Workbook(); var worksheet = workbook.addWorksheet('sheet', { pageSetup:{paperSize: 9, orientation:' ...

Explore RxJs DistinctUntilChanged for Deep Object Comparison

I have a scenario where I need to avoid redundant computations if the subscription emits the same object. this.stateObject$ .pipe(distinctUntilChanged((obj1, obj2) => JSON.stringify({ obj: obj1 }) === JSON.stringify({ obj: obj2 }))) .subscribe(obj =& ...

Strategies for redirecting search queries when adding a new path

Issue I am facing a challenge with pushing a new path to the URI while maintaining existing search queries. For example: Current URL: https://example.com/foo?bar=123&foobar=123 When I use history.push('newPath'), I end up with https://exa ...

Transform tree-like JSON array with nested arrays into flat JSON array

I have an array tree in JSON format with potentially unlimited nesting: const namesArrayTree = [ { "name": "Peter" }, { "name": "folder1", "isArray": true, " ...

What steps can be taken to enable users to draw a path on a Google Map?

I'm working on a new project for a Facebook app that will allow users to map out their marathon route using Google Maps. I plan to utilize mySQL database records to store fixed points along the path (such as specific locations based on latitude and lo ...

"Unfortunately, Azure Web Static Apps do not have the capability to access .env files that are prefixed with NEXT

Suppose I have an .env file set up like this: NEXT_PUBLIC_API_BASE_PATH = value1 While this .env is functioning correctly in my local environment, once deployed to Azure Web Static Apps and added to the configurationhttps://i.sstatic.net/eqiYn.png My app ...

What is the best way to vertically flip a background image that is repeating along the y axis in CSS?

I am in the process of developing a mobile web app and I need assistance with flipping the background image when it repeats along the y-axis. Can someone guide me on how to achieve this using CSS or JavaScript? https://i.stack.imgur.com/b107V.jpg var el ...

Tips on saving a cookie using universal-cookie

I followed a solution on Stack Overflow to set a cookie in my React application. However, the cookie expires with the session. Is there a way I can make this cookie persist beyond the session so it remains even when the browser is closed and reopened? ex ...

Using sql.js to import CSV files into SQLite databases

Is it possible to import a CSV file into a SQLite database using JavaScript instead of the command line? I am currently utilizing the sql.js library to work with SQLite in Javascript. I appreciate any help or suggestions on how to accomplish this task. Th ...

Sort an array by mapping it in decreasing order based on the total sum of its elements

I came across a JSON structure that looks like the following: { "user": [ {"username": "x1", "pfp": "", "scores": [{"easy": 10, "normal": 1, "hard": 2, "oni&q ...

Create a distributive and an NPM package using one source code

Creating small open source tools is a passion of mine, and I strive to provide the best experience for my users. My packages usually consist of just one function, so here's what I aim to offer: A JavaScript file that users can easily add by including ...

Generating ChartJS in Real-time

I have a straightforward form where the user selects a start date and an end date. Once these dates are selected, the tool automatically fetches data from a website in JSON format. Below is the code for my Angular controller: (function () { angular.m ...

What is the reason for this JavaScript code not activating the input field (aspx)?

Thank you for taking the time to review this. I understand that for most of you client side scripting experts, this task is a breeze. However, all I am trying to achieve is to display a message at the top notifying the user that their click has been regist ...

The importance of manually loading extensions and utilizing Ajax effectively for renderPartial

Within my yii application, I have implemented Tabs and am loading content via ajax using renderPartial(). To prevent redundant script loading, I have set processOutput to false. As a result, I aim to manually load all necessary scripts once on the index pa ...

Encountering a blank or 404 error page in React after running npm build - let's troubleshoot where the issue might be

Upon running npm build(react), my index.html displays a blank page. To address this issue, I initially attempted the following steps: Adding the following line in package.json homepage : "./" or "." or "absolute file PATH" ...

What could be causing the React state to not function properly when using data from an external class?

Recently diving into the world of Javascript and React, I decided to challenge myself by creating a basic calculator. My strategy was to separate the calculator logic into its own class. As I am currently testing it out, I encountered a peculiar issue. It ...

Generate dynamic Bootstrap Carousel slides with unique hashtag URLs

I've been attempting to connect to various slides within a bootstrap carousel from a different page but have had no success. Here is an example of what I'm trying to achieve: <a href="services#slide2">Link to Slide 2</a> For refere ...

Why does the MEAN Stack continue to route using the '#' symbol in the URL?

Currently navigating the realm of back end development. Started off by following a guide on express from thinkster. In need of some clarification. Initially, I grasped that front-end and back-end routing serve different purposes. Front-end routing relates ...

Is it possible to meta-refresh a page for redirection?

When creating a webpage, I included a META tag like this: <META http-equiv="refresh" content="5;URL=http://www.google.com"> The issue is that mobile browsers do not support this meta tag. It redirects properly on web browsers, but not on mobile dev ...

The Keyup Filter in the FromEvent function is malfunctioning and not behaving as anticipated

I have created a simple search function for my app using the FromEvent KeyUp and debounceTime features as shown in the code below: <input matInput #inputSearch> @ViewChild('inputSearch', { static: false }) input: ElementRef; fromEvent(th ...