skip to Main Content

I want to retrieve data from mongoDB, a collection of products, But instead of an array or an object with data, I get an HTML template. What can this be related to? The database is connected, I checked.
Screenshots below.

model product

const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
  title: String,
  price: Number,
  quantity: Number,
});

const Product = mongoose.model("products", productSchema);

module.exports =  Product ;

server

const express = require('express');
const app = express();
const  Product  = require("./models/Products");

app.get("/api/products", (req, res) => {
  Product.find((error, data) => {
    if (!error) {
      res.status(200).send(data);
    } else {
      res.status(500).send(error);
    }
  });
});

axios from the client side

import axios from "axios";

const axiosInstance = axios.create({
  baseURL: 'http://localhost:8080',
});

export default axiosInstance;

client

useEffect(() => {
    const fetchData = async () => {
      const data = await axios.get("/api/products");
      console.log('product >>>', data);
    }
    fetchData();
  }, []);

mongoDB, collection product

enter image description here

screenshot

enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    I found a solution to this problem. Model.find() no longer accepts callbacks, that's why the error occurs. It is enough to specify then after find, and everything will work Model.find().then((data) => {}))


  2. Axios baseURL was not set.
    You can create an axiosInstance with baseURL and use it to call the api.

    const axiosInstance = axios.create({
      baseURL: 'http://localhost:8080',
      headers: {
        Authorization: '',
        'Content-Type': 'application/json',
      },
    });
    axiosInstance.get('/api/products');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search