You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MERN栈库存系统:通过ObjectId查产品前端请求失败排查

问题:MERN栈库存管理系统查看产品返回“无匹配产品”但Postman测试正常

我使用MERN栈开发库存管理系统,尝试查看产品时始终返回“无匹配产品”,但数据库集合中存在匹配的产品,且用Postman测试后端接口完全正常。

前端代码

const ViewProduct = () => {
  const {prodID} = useParams()
  const [product, setProduct] = useState(null);
  const [isCalling, setIsCalling] = useState(false);
 

  useEffect(() => {
    const getProduct = async () => {
      setIsCalling(true);

      await axios.get('https://localhost:4000/api/products/',{params:prodID}
      ).then(response => {
        setProduct(response.data)
      }).catch(error => {
        console.error(error);
      })

      setIsCalling(false);
    };

    getProduct();
  }, [prodID]);

  if (isCalling) {
    return <div>Loading...</div>;
  }

  if (!product) {
    return <div>No matching products</div>;
  }

  return (
    <>
    <div>
      <h2>{product.name}</h2>
      <p>Product ID: {prodID}</p>
      <p>Description: {product.descr.join(', ')}</p>
      <p>Type: {product.type}</p>
      <p>Sub-type: {product.sub_type}</p>
      <p>No of Stock Remaining: {product.noOfStockRemaining}</p>
      <p>Archived: {product.archived ? 'Yes' : 'No'}</p>
      <p>Archived On: {product.archived_on}</p>
      <Button>Delete</Button>
      <Button >Add Stock</Button>
      <Button>Back To Inventory</Button>

    </div>
    </>

  );
};

后端代码

const getAProduct = async (req, res) => {
    const { id } = req.params
    //revisit ths validation after importing nanoid
    if (!mongoose.Types.ObjectId.isValid(id)) {
        return res.json({ error: 'no matching products' })
    }
    const product = await Product.findById(id)

    if (!product) {
        return res.json({ error: 'no matching products' })
    }

    res.json(product)
}

请求日志中间件

app.use((req, res, next) =>{
    console.log(req.path, req.method)
    next()
})

Postman测试时该中间件能输出请求信息,但前端发起请求时无输出。

更新:跨域错误

控制台出现以下跨域错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:4000/api/products/. (Reason: CORS request did not succeed). Status code: (null)

我已安装并配置CORS,且其他请求正常,添加withCredentials:true也无效。

问题解决

编辑:问题已解决,是axios请求URL将http误写为https。


内容的提问来源于stack exchange,提问作者Styx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 21:12:01