NodeJS Axios GET请求返回Next.js中的API路由404错误

mfpqipee  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(146)

我正在构建一个Next.js应用程序,我试图使用Axios从API路由获取产品细节。然而,我遇到了一个“请求失败,状态代码为404”的错误,这表明没有找到所请求的资源。
x1c 0d1x的数据
以下是所涉及文件的相关代码片段:

1.pages/admin/dashboard/product/create.js:

字符串
这是Axios GET请求获取产品详细信息的地方。在发出请求之前,我已经验证了product.parent值包含有效的产品ID。

/** @format */

import db from "@/utils/db";
import styles from "../../../../styles/products.module.scss";
import Layout from "@/components/admin/layout";
import Product from "@/models/Product";
import Category from "@/models/Category";
import { useEffect, useState } from "react";
import axios from "axios";
import * as Yup from "yup";
import { Form, Formik } from "formik";
import SingularSelect from "@/components/selects/SingularSelect";

const initialState = {
    name: "",
    description: "",
    brand: "",
    sku: "",
    discount: 0,
    images: [],
    description_images: [],
    parent: "",
    category: "",
    subCategories: [],
    color: {
        color: "",
        image: "",
    },
    sizes: [
        {
            size: "",
            qty: "",
            price: "",
        },
    ],
    details: [
        {
            name: "",
            value: "",
        },
    ],
    questions: [
        {
            question: "",
            answer: "",
        },
    ],
    shippingFee: "",
};
export default function create({ parents, categories }) {
    const [product, setProduct] = useState(initialState);
    const [subs, setSubs] = useState([]);
    const [colorImage, setColorImage] = useState("");
    const [images, setImages] = useState([]);
    const [description_images, setDescription_images] = useState("");
    const [loading, setLoading] = useState(false);
    console.log(product);
    useEffect(() => {
        const getParentData = async () => {
          const { data } = await axios.get(`/api/product/${product.parent}`);
          console.log(data);
          if (data) {
            setProduct({
              ...product,
              name: data.name,
              description: data.description,
              brand: data.brand,
              category: data.category,
              subCategories: data.subCategories,
              questions: [],
              details: [],
            });
          }
        };
        getParentData();
      }, [product.parent]);
    useEffect(() => {
        async function getSubs() {
            const { data } = await axios.get("/api/admin/subCategory", {
                params: {
                    category: product.category,
                },
            });
            setSubs(data);
        }
            getSubs();
    }, [product.category]);
    const handleChange = (e) => {
        const { value, name } = e.target;
        setProduct({ ...product, [name]: value });
    };
    const validate = Yup.object({});
    const createProduct = async () => {};
    return (
        <Layout>
            <div className={styles.header}>create product</div>
            <Formik
                enableReinitialize
                initialValues={{
                    name: product.name,
                    brand: product.brand,
                    description: product.description,
                    category: product.category,
                    subCategories: product.subCategories,
                    parent: product.parent,
                    sku: product.sku,
                    discount: product.discount,
                    color: product.color.color,
                    imageInputFile: "",
                    styleInout: "",
                }}
                validationSchema={validate}
                onSubmit={() => {
                    createProduct();
                }}
            >
                {(fromik) => (
                    <Form>
                        {/* <Images name="imageInputFile"
          header="Product Carousel Image"
          text="add images"
          images={images}
          setImages={setImages}
          setColorImage={setColorImage}
          /> */}
                        <div className={styles.flex}>
                            {product.color.image && (
                                <img
                                    src={product.color.image}
                                    className={styles.image_span}
                                    alt=''
                                />
                            )}
                            {product.color.color && (
                                <span
                                    className={styles.color_span}
                                    style={{ background: `${product.color.color}` }}
                                ></span>
                            )}
                            {/* <Colors
                name="color"
                product={product}
                setProduct={setProduct}
                colorImage={colorImage}
              />
              <Style
                name="styleInput"
                product={product}
                setProduct={setProduct}
                colorImage={colorImage}
              /> */}
                            <SingularSelect
                                name='parent'
                                value={product.parent}
                                placeholder='Parent product'
                                data={parents}
                                header='Add to an existing product'
                                handleChange={handleChange}
                            />
                        </div>
                    </Form>
                )}
            </Formik>
        </Layout>
    );
}

export async function getServerSideProps(ctx) {
    db.connectDb();
    const results = await Product.find().select("name subProducts").lean();
    const categories = await Category.find().lean();
    db.disconnectDb();
    return {
        props: {
            parents: JSON.parse(JSON.stringify(results)),
            categories: JSON.parse(JSON.stringify(categories)),
        },
    };
}
2.pages/api/product/[id].js:

的数据
这是负责根据提供的ID获取产品详细信息的API路由文件。我已经检查了这个文件,它似乎被正确地实现了。

import nc from "next-connect";
import db from "../../../utils/db";
import Product from "../../../models/Product";

const handler = nc();

handler.get(async (req, res) => {
  try {
    db.connectDb();
    const id = req.query.id;
    const style = req.query.style || 0;
    const size = req.query.size || 0;
    const product = await Product.findById(id).lean();
    let discount = product.subProducts[style].discount;
    let priceBefore = product.subProducts[style].sizes[size].price;
    let price = discount ? priceBefore - priceBefore / discount : priceBefore;
    db.disconnectDb();
    return res.json({
      _id: product._id,
      style: Number(style),
      name: product.name,
      description: product.description,
      slug: product.slug,
      sku: product.subProducts[style].sku,
      brand: product.brand,
      category: product.category,
      subCategories: product.subCategories,
      shipping: product.shipping,
      images: product.subProducts[style].images,
      color: product.subProducts[style].color,
      size: product.subProducts[style].sizes[size].size,
      price,
      priceBefore,
      quantity: product.subProducts[style].sizes[size].qty,
    });
  } catch (error) {
    return res.status(500).json({ message: error.message });
  }
});

export default handler;
3.pages/api/admin/subCategory.js:
handler.get(async (req, res) => {
  try {
    const { category } = req.query;
    console.log(category);
    if (!category) {
      return res.json([]);
    }
    db.connectDb();
    const results = await SubCategory.find({ parent: category }).select("name");
    console.log(results);
    db.disconnectDb();
    return res.json(results);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

我已经检查了API路由文件(pages/api/product/[id].js),它似乎被正确地实现为基于提供的ID获取产品细节。但是,当从create.js发出Axios GET请求时,我得到了404错误响应。
我怀疑Axios处理GET请求的方式可能有问题,或者我的API路由实现可能有问题。我不确定如何继续调试此问题。
有人能指导我如何解决和修复Next.js应用程序中Axios GET请求的“404”错误吗?如有任何见解或建议,将不胜感激。提前感谢您的帮助!



aamkag61

aamkag611#

一个可能的原因可能是,在create.js组件中,您正在使用useEffect基于product.parent获取父数据。但是,您在URL中使用它而没有检查它是否是有效值。如果parent的值无效,则可能导致404错误。您可以添加一个条件,在发出GET请求之前检查product.parent不为空,

useEffect(() => {
    const getParentData = async () => {
        if (product.parent) { // Check if product.parent is not empty
            try {
                // the axios call
                }
            } catch (error) {
                console.error("Error fetching parent data:", error)
            }
        }
    }
    getParentData()
}, [product.parent])

字符串
或者类似的东西

useEffect(() => {
    const getParentData = async () => {
        try {
         // ... axios call
        } catch (error) {
            console.error("Error fetching parent data:", error)
        }
    }
    
    if (product.parent) { // Call the function only when product.parent is not empty
        getParentData()
    }
}, [product.parent])


还要仔细检查db.connectDb()函数。您是否应该等待连接建立后再继续?

await db.connectDb(); // Connect to the database
 await db.disconnectDb(); // Disconnect from the database

相关问题