为什么next.js中的API路由会出现404错误

qfe3c7zg  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(242)

为什么我的fetch请求给我错误“GET http://localhost:3000/api/db/getRideTypes 404(Not Found)”当尝试从sanity客户端获取数据时。
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)
          }
        })()
    }, [])

getRideTypes.js是

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

getRideTypes.js位于API文件夹中,其结构为src/app/pages/api/db/getRideTypes.js。src在根目录中。RideSelector.js位于components文件夹中,该文件夹与src文件夹位于同一根目录中。

nzrxty8p

nzrxty8p1#

请求路径无效,正确路径应为/api/db/getRideTypes。另外,取消对ride selectors文件顶部的"use client";指令的注解,因为您在该组件中使用了state。

相关问题